-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_ip.c
154 lines (126 loc) · 2.73 KB
/
check_ip.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
static inline unsigned long digits_to_num(char *s, size_t num_digits)
{
assert(num_digits >= 1);
assert(num_digits <= 3);
unsigned long v = 0;
switch (num_digits)
{
case 3:
v += (s[0] - '0') * 100;
v += (s[1] - '0') * 10;
v += (s[2] - '0') * 1;
break;
case 2:
v += (s[0] - '0') * 10;
v += (s[1] - '0') * 1;
break;
case 1:
v += (s[0] - '0');
break;
default:
break;
}
return v;
}
bool is_valid_ipv4(char *addr)
{
if (!addr)
{
return false;
}
char *start = addr;
char *p = addr;
int num_components = 0;
bool startswith_0 = false;
while (*p != '\0')
{
if ((p - start) == 0)
{
if (*p == '0')
{
startswith_0 = true;
p++;
continue;
}
else if (*p == '1' || *p == '2')
{
p++;
continue;
}
return false;
}
assert((p - start) >= 1);
if (*p == '0')
{
/* 001.1.1.1 */
if (startswith_0)
{
return false;
}
/* 1230.1.1.1 */
if ((p - start) >= 3)
{
return false;
}
/* 10.100.1.1 */
p++;
continue;
}
if (*p >= '1' && *p <= '9')
{
/* 01.1.1.1 */
if (startswith_0)
{
return false;
}
/* 1234.0.0.0 */
if ((p - start) >= 3)
{
return false;
}
p++;
continue;
}
if (*p == '.')
{
/* 123.123.123.123. */
if (num_components == 3)
{
return false;
}
assert((p - start) >= 1);
assert((p - start) <= 3);
unsigned long v = digits_to_num(start, p - start);
if (v > 255)
{
return false;
}
num_components++;
p++;
start = p;
startswith_0 = false;
continue;
}
return false;
}
/* 123 / 123.123 / etc. */
if (num_components != 3)
{
return false;
}
/* 123.123.123. */
if ((p - start) == 0)
{
return false;
}
/* 123.123.123.123 */
unsigned long v = digits_to_num(start, p - start);
if (v > 255)
{
return false;
}
return true;
}