1 #include <sys/socket.h>
2 #include <netinet/in.h>
8 #include "stdio_impl.h"
10 int __lookup_serv(struct service buf[static MAXSERVS], const char *name, int proto, int socktype, int flags)
15 unsigned long port = 0;
40 if (name) return EAI_SERVICE;
43 buf[0].socktype = socktype;
48 if (!*name) return EAI_SERVICE;
49 port = strtoul(name, &z, 10);
52 if (port > 65535) return EAI_SERVICE;
53 if (proto != IPPROTO_UDP) {
55 buf[cnt].socktype = SOCK_STREAM;
56 buf[cnt++].proto = IPPROTO_TCP;
58 if (proto != IPPROTO_TCP) {
60 buf[cnt].socktype = SOCK_DGRAM;
61 buf[cnt++].proto = IPPROTO_UDP;
66 if (flags & AI_NUMERICSERV) return EAI_SERVICE;
68 size_t l = strlen(name);
70 unsigned char _buf[1032];
71 FILE _f, *f = __fopen_rb_ca("/etc/services", &_f, _buf, sizeof _buf);
72 if (!f) return EAI_SERVICE;
74 while (fgets(line, sizeof line, f) && cnt < MAXSERVS) {
75 if ((p=strchr(line, '#'))) *p++='\n', *p=0;
77 /* Find service name */
78 for(p=line; (p=strstr(p, name)); p++) {
79 if (p>line && !isspace(p[-1])) continue;
80 if (p[l] && !isspace(p[l])) continue;
85 /* Skip past canonical name at beginning of line */
86 for (p=line; *p && !isspace(*p); p++);
88 port = strtoul(p, &z, 10);
89 if (port > 65535 || z==p) continue;
90 if (!strncmp(z, "/udp", 4)) {
91 if (proto == IPPROTO_TCP) continue;
93 buf[cnt].socktype = SOCK_DGRAM;
94 buf[cnt++].proto = IPPROTO_UDP;
96 if (!strncmp(z, "/tcp", 4)) {
97 if (proto == IPPROTO_UDP) continue;
99 buf[cnt].socktype = SOCK_STREAM;
100 buf[cnt++].proto = IPPROTO_TCP;
104 return cnt > 0 ? cnt : EAI_SERVICE;