当前位置: 技术问答>linux和unix
谁有判断一个字符串是合法IP地址的函数
来源: 互联网 发布时间:2017-01-14
本文导语: IP地址是“.”分开的字符串,如“xx.xx.xx.xx”,求判断IP地址是否合法的源码。我自己写了几个,都不太完备,如: //检查是否是合法的IP地址,是,返回0,否则,返回-1 int ip_addr_check(const char * str) { int dot_nums...
IP地址是“.”分开的字符串,如“xx.xx.xx.xx”,求判断IP地址是否合法的源码。我自己写了几个,都不太完备,如:
//检查是否是合法的IP地址,是,返回0,否则,返回-1
int ip_addr_check(const char * str)
{
int dot_nums, i, len;
char temp;
char * p;
dot_nums = 0;
int sect, sect_len;
char sect_str[20];
if(str == NULL)
{
return -1;
}
p = str;
sect_len = 0;
if((len = strlen(str)) > 19)
{
printf("ip addr too long %dn",len);
return -1;
}
for(i = 0; i 255 || ( sect_str[0] == ''))
{
printf(" %s sect too largen",str);
return -1;
}
dot_nums++;
if(dot_nums > 3)
{
printf(" %s too much dotsn",str);
return -1;
}
else if( dot_nums == 3)
{
sect = myaton(p);
if(sect > 255 || (*p == ''))
{
printf(" %s sect too largen",str);
return -1;
}
}
}else if(temp '9')
{
printf(" %s out of rangen",str);
return -1;
}
else{
sect_str[sect_len] = temp;
sect_len++;
}
}
if(dot_nums != 3)
{
printf(" %s too %d dotsn",str , dot_nums);
return -1;
}
return 0;
}
|
那你自己去编码呗,没有难度的东西,笔试题都是这玩意。
|
#define NON_ZERO_DIGIT(c) ( ((c) > '0') && ((c) = '0') && ((c) 15)
{
return false;
}
else
{
int iDotCount = 0;
string::const_iterator iter = strIp.begin();
for (; iter 255 || iIp1 > 255 || iIp2 > 255 || iIp3 > 255)
{
return false;
}
return true;
}
}
|
int if_a_string_is_a_valid_ipv4_address(const char *str)
{
struct in_addr addr;
int ret;
volatile int local_errno;
errno = 0;
ret = inet_pton(AF_INET, str, &addr);
local_errno = errno;
if (ret > 0)
//dprintf(""%s" is a valid IPv4 addressn", str);
//printf(""%s" is a valid IPv4 addressn", str);
;
else if (ret