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*
getservbyname(char * name,char * proto)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 _syserrno();
48 return 0;
49 }
50
51 /* construct the query, always expect an ip# back */
52 if(num)
53 snprintf(buf, sizeof buf, "!port=%s %s=*", name, proto);
54 else
55 snprintf(buf, sizeof buf, "!%s=%s port=*", proto, name);
56
57 /* query the server */
58 if(write(fd, buf, strlen(buf)) < 0){
59 _syserrno();
60 return 0;
61 }
62 lseek(fd, 0, 0);
63 for(i = 0; i < sizeof(buf)-1; i += m){
64 m = read(fd, buf+i, sizeof(buf) - 1 - i);
65 if(m <= 0)
66 break;
67 buf[i+m++] = ' ';
68 }
69 close(fd);
70 buf[i] = 0;
71
72 /* parse the reply */
73 nn = na = 0;
74 for(bp = buf;;){
75 p = strchr(bp, '=');
76 if(p == 0)
77 break;
78 *p++ = 0;
79 if(strcmp(bp, proto) == 0){
80 if(nn < Nname)
81 nptr[nn++] = p;
82 } else if(strcmp(bp, "port") == 0){
83 s.s_port = htons(atoi(p));
84 }
85 while(*p && *p != ' ')
86 p++;
87 if(*p)
88 *p++ = 0;
89 bp = p;
90 }
91 if(nn+na == 0)
92 return 0;
93
94 nptr[nn] = 0;
95 s.s_aliases = nptr;
96 if(s.s_name == 0)
97 s.s_name = nptr[0];
98
99 return &s;
100 }
101