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 flags)
15 unsigned long port = 0;
18 if (!*name) return EAI_SERVICE;
19 port = strtoul(name, &z, 10);
22 if (port > 65535) return EAI_SERVICE;
23 if (proto != IPPROTO_UDP) {
25 buf[cnt++].proto = IPPROTO_TCP;
27 if (proto != IPPROTO_TCP) {
29 buf[cnt++].proto = IPPROTO_UDP;
34 if (flags & AI_NUMERICSERV) return EAI_SERVICE;
36 size_t l = strlen(name);
38 unsigned char _buf[1032];
39 FILE _f, *f = __fopen_rb_ca("/etc/services", &_f, _buf, sizeof _buf);
40 if (!f) return EAI_SERVICE;
42 while (fgets(line, sizeof line, f) && cnt < MAXSERVS) {
43 if ((p=strchr(line, '#'))) *p++='\n', *p=0;
45 /* Find service name */
46 for(p=line; (p=strstr(p, name)); p++) {
47 if (p>line && !isspace(p[-1])) continue;
48 if (p[l] && !isspace(p[l])) continue;
53 /* Skip past canonical name at beginning of line */
54 for (p=line; *p && !isspace(*p); p++);
56 port = strtoul(p, &z, 10);
57 if (port > 65535 || z==p) continue;
58 if (!strncmp(z, "/udp", 4)) {
59 if (proto == IPPROTO_TCP) continue;
61 buf[cnt++].proto = IPPROTO_UDP;
63 if (!strncmp(z, "/tcp", 4)) {
64 if (proto == IPPROTO_UDP) continue;
66 buf[cnt++].proto = IPPROTO_TCP;
70 return cnt > 0 ? cnt : EAI_SERVICE;