remove an unnecessary check in inet_pton
[musl] / src / network / inet_pton.c
1 #include <sys/socket.h>
2 #include <arpa/inet.h>
3 #include <ctype.h>
4 #include <errno.h>
5 #include <string.h>
6
7 static int hexval(unsigned c)
8 {
9         if (c-'0'<10) return c-'0';
10         c |= 32;
11         if (c-'a'<6) return c-'a'+10;
12         return -1;
13 }
14
15 int inet_pton(int af, const char *restrict s, void *restrict a0)
16 {
17         uint16_t ip[8];
18         unsigned char *a = a0;
19         int i, j, v, d, brk=-1, need_v4=0;
20
21         if (af==AF_INET) {
22                 for (i=0; i<4; i++) {
23                         for (v=j=0; j<3 && isdigit(s[j]); j++)
24                                 v = 10*v + s[j]-'0';
25                         if (j==0 || (j>1 && s[0]=='0') || v>255) return 0;
26                         a[i] = v;
27                         if (s[j]==0 && i==3) return 1;
28                         if (s[j]!='.') return 0;
29                         s += j+1;
30                 }
31                 return 0;
32         } else if (af!=AF_INET6) {
33                 errno = EAFNOSUPPORT;
34                 return -1;
35         }
36
37         if (*s==':' && *++s!=':') return 0;
38
39         for (i=0; ; i++) {
40                 if (s[0]==':' && brk<0) {
41                         brk=i;
42                         ip[i]=0;
43                         if (!*++s) break;
44                         continue;
45                 }
46                 for (v=j=0; j<4 && (d=hexval(s[j]))>=0; j++)
47                         v=16*v+d;
48                 if (j==0) return 0;
49                 ip[i] = v;
50                 if (!s[j] && (brk>=0 || i==7)) break;
51                 if (i==7) return 0;
52                 if (s[j]!=':') {
53                         if (s[j]!='.' || (i<6 && brk<0)) return 0;
54                         need_v4=1;
55                         i++;
56                         break;
57                 }
58                 s += j+1;
59         }
60         if (brk>=0) {
61                 memmove(ip+brk+7-i, ip+brk, 2*(i+1-brk));
62                 for (j=0; j<7-i; j++) ip[brk+j] = 0;
63         }
64         for (j=0; j<8; j++) {
65                 *a++ = ip[j]>>8;
66                 *a++ = ip[j];
67         }
68         if (need_v4 && inet_pton(AF_INET, (void *)s, a-4) <= 0) return 0;
69         return 1;
70 }