expose FNM_* extensions in fnmatch.h without _GNU_SOURCE
[musl] / src / network / __ipparse.c
1 #include <string.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <arpa/inet.h>
7 #include "__dns.h"
8
9 int __ipparse(void *dest, int family, const char *s0)
10 {
11         const char *s = s0;
12         unsigned char *d = dest;
13         unsigned long a[16] = { 0 };
14         char *z;
15         int i;
16
17         if (family == AF_INET6) goto not_v4;
18
19         for (i=0; i<4; i++) {
20                 a[i] = strtoul(s, &z, 0);
21                 if (z==s || (*z && *z != '.') || !isdigit(*s)) {
22                         if (family == AF_INET) return -1;
23                         goto not_v4;
24                 }
25                 if (!*z) break;
26                 s=z+1;
27         }
28         if (i==4) return -1;
29         switch (i) {
30         case 0:
31                 a[1] = a[0] & 0xffffff;
32                 a[0] >>= 24;
33         case 1:
34                 a[2] = a[1] & 0xffff;
35                 a[1] >>= 16;
36         case 2:
37                 a[3] = a[2] & 0xff;
38                 a[2] >>= 8;
39         }
40         ((struct sockaddr_in *)d)->sin_family = AF_INET;
41         d = (void *)&((struct sockaddr_in *)d)->sin_addr;
42         for (i=0; i<4; i++) {
43                 if (a[i] > 255) return -1;
44                 d[i] = a[i];
45         }
46         return 0;
47
48 not_v4:
49         s = s0;
50         ((struct sockaddr_in6 *)d)->sin6_family = AF_INET6;
51         return inet_pton(AF_INET6, s, (void *)&((struct sockaddr_in6 *)d)->sin6_addr) <= 0 ? -1 : 0;
52 }