]> git.lizzy.rs Git - plan9front.git/blob - sys/src/ape/lib/bsd/getservbyname.c
ape: Add mkstemp to /sys/src/ape/lib/ap/gen/mkfile
[plan9front.git] / sys / src / ape / lib / bsd / getservbyname.c
1 /* posix */
2 #include <sys/types.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <fcntl.h>
7 #include <string.h>
8 #include <errno.h>
9 #include <ctype.h>
10
11 /* bsd extensions */
12 #include <sys/uio.h>
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <netdb.h>
16
17 #include "priv.h"
18
19 enum
20 {
21         Nname= 6,
22 };
23
24 /*
25  *  for inet addresses only
26  */
27 struct servent*
28 getservbyname(char *name, char *proto)
29 {
30         int i, fd, m, num;
31         char *p, *bp;
32         int nn, na;
33         static struct servent s;
34         static char buf[1024];
35         static char *nptr[Nname+1];
36
37         num = 1;
38         for(p = name; *p; p++)
39                 if(!isdigit(*p))
40                         num = 0;
41
42         s.s_name = 0;
43
44         /* connect to server */
45         fd = open("/net/cs", O_RDWR);
46         if(fd < 0)
47                 return 0;
48
49         /* construct the query, always expect an ip# back */
50         if(num)
51                 snprintf(buf, sizeof buf, "!port=%s %s=*", name, proto);
52         else
53                 snprintf(buf, sizeof buf, "!%s=%s port=*", proto, name);
54
55         /* query the server */
56         if(write(fd, buf, strlen(buf)) < 0){
57                 close(fd);
58                 return 0;
59         }
60         lseek(fd, 0, 0);
61         for(i = 0; i < sizeof(buf)-1; i += m){
62                 m = read(fd, buf+i, sizeof(buf) - 1 - i);
63                 if(m <= 0)
64                         break;
65                 buf[i+m++] = ' ';
66         }
67         close(fd);
68         buf[i] = 0;
69
70         /* parse the reply */
71         nn = na = 0;
72         for(bp = buf;;){
73                 p = strchr(bp, '=');
74                 if(p == 0)
75                         break;
76                 *p++ = 0;
77                 if(strcmp(bp, proto) == 0){
78                         if(nn < Nname)
79                                 nptr[nn++] = p;
80                 } else if(strcmp(bp, "port") == 0){
81                         s.s_port = htons(atoi(p));
82                 }
83                 while(*p && *p != ' ')
84                         p++;
85                 if(*p)
86                         *p++ = 0;
87                 bp = p;
88         }
89         if(nn+na == 0)
90                 return 0;
91
92         nptr[nn] = 0;
93         s.s_aliases = nptr;
94         if(s.s_name == 0)
95                 s.s_name = nptr[0];
96
97         return &s;
98 }