如何判断合法的IP地址,尽可能考虑各种情况
判断IPV4的地址是否合法的程序
只对IP地址如下规则做了判断:
IP地址的规则是: (1 ~ 255).(0 ~ 255).(0 ~ 255).(0 ~ 255)。例如192.168.2.1
#include<stdio.h>
#include<ctype.h>
static int CountPoint(const char* str)//计算字符串的.的个数
{
int count = 0;
while (*str != '\0')
{
if (*str == '.')
count++;
str++;
}
return count;
}
//判断IPV4的地址是否合法的程序
//只对IP地址如下规则做了判断:
//IP地址的规则是: (1~255).(0~255).(0~255).(0~255)。例如192.168.2.1
bool IsIP(const char* str)
{
const char* p = NULL;
int num = 0;
if (str == NULL)
{
return false;
}
if (CountPoint(str) != 3)//IP地址只有3个.号
{
return false;
}
if (str[0] == '0')//IP地址起始不能为0
{
return false;
}
while (*str != '\0')
{
if (isdigit(*str))
{
num = num * 10 + *str - '0';
}
else if (*str != '.' || num > 255)
{
return false;
}
else
{
num = 0;
}
str++;
}
if (num > 255)//处理尾部数据
return false;
return true;
}
int main()
{
const char* str[] = { "192.168.1.1","1.0.0","1.0.0.0","256.1.2.1","192.1.1.256" };
for (int i = 0; i < sizeof(str) / sizeof(str[0]); i++)
{
if (IsIP(str[i]))
{
printf("%s 是合法的IP\n", str[i]);
}
else
{
printf("%s 不是合法的IP\n", str[i]);
}
}
return 0;
}