C语言检查ip是否合法

时间:2023-03-08 18:55:30

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

 #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h> bool isVaildIp(const char *ip)
{
int dots = ; /*字符.的个数*/
int setions = ; /*ip每一部分总和(0-255)*/ if (NULL == ip || *ip == '.') { /*排除输入参数为NULL, 或者一个字符为'.'的字符串*/
return false;
} while (*ip) { if (*ip == '.') {
dots ++;
if (setions >= && setions <= ) { /*检查ip是否合法*/
setions = ;
ip++;
continue;
}
return false;
}
else if (*ip >= '' && *ip <= '') { /*判断是不是数字*/
setions = setions * + (*ip - ''); /*求每一段总和*/
} else
return false;
ip++;
}
   /*判断IP最后一段是否合法*/
if (setions >= && setions <= ) {
if (dots == ) {
return true;
}
} return false;
} void help()
{
printf("Usage: ./test <ip str>\n");
exit();
} int main(int argc, char **argv)
{
if (argc != ) {
help();
} if (isVaildIp(argv[])) {
printf("Is Vaild Ip-->[%s]\n", argv[]);
} else {
printf("Is Invalid Ip-->[%s]\n", argv[]);
} return ;
}

运行结果:

 [root@localhost isvildip]# ./test 192.168.1.1
Is Vaild Ip-->[192.168.1.1]
[root@localhost isvildip]# ./test 192.168.1.256
Is Invalid Ip-->[192.168.1.256]
[root@localhost isvildip]#