C语言检查ip是否合法

在工做当中咱们常常会遇到这种问题:判断一个输入的字符串是否为合法的IP地址,下面是一个测试小程序:小程序

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 #include <stdbool.h>
 5 
 6 bool isVaildIp(const char *ip)
 7 {
 8     int dots = 0; /*字符.的个数*/
 9     int setions = 0; /*ip每一部分总和(0-255)*/ 
10 
11     if (NULL == ip || *ip == '.') { /*排除输入参数为NULL, 或者一个字符为'.'的字符串*/ 
12         return false;
13     }   
14 
15     while (*ip) {
16 
17         if (*ip == '.') {
18             dots ++; 
19             if (setions >= 0 && setions <= 255) { /*检查ip是否合法*/
20                 setions = 0;
21                 ip++;
22                 continue;
23             }   
24             return false;
25         }   
26         else if (*ip >= '0' && *ip <= '9') { /*判断是否是数字*/
27             setions = setions * 10 + (*ip - '0'); /*求每一段总和*/
28         } else 
29             return false;
30         ip++;   
31     }   
32    /*判断IP最后一段是否合法*/ 
33     if (setions >= 0 && setions <= 255) {
34         if (dots == 3) {
35             return true;
36         }   
37     }   
38 
39     return false;
40 }
41 
42 void help()
43 {
44     printf("Usage: ./test <ip str>\n");
45     exit(0);
46 }
47 
48 int main(int argc, char **argv)
49 {
50     if (argc != 2) {
51         help(); 
52     }   
53 
54     if (isVaildIp(argv[1])) {
55         printf("Is Vaild Ip-->[%s]\n", argv[1]);
56     } else {
57         printf("Is Invalid Ip-->[%s]\n", argv[1]);
58     }   
59 
60     return 0;
61 }

运行结果:测试

1 [root@localhost isvildip]# ./test 192.168.1.1
2 Is Vaild Ip-->[192.168.1.1]
3 [root@localhost isvildip]# ./test 192.168.1.256
4 Is Invalid Ip-->[192.168.1.256]
5 [root@localhost isvildip]#