您的位置:首页 > 其它

判断输入的ip字符串格式的合法性

2014-06-15 17:24 369 查看
ipv4的ip格式共32位,每8位用一个10进制数表示,中间为.如192.168.8.104

字符串输入正确,如192.168.8.104

输出YES

不正确,如192.c.8.104或192. 258.8.104呀192 .168.8.104

输出 NO

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int isIn255(int ipSeg[],int cnt)
{
int value;
if(cnt==1)
{
value=ipSeg[0];
if(value>=0&&value<256)
return 1;
return 0;
}
else if(cnt==2)
{
value=ipSeg[0]*10+ipSeg[1];
if(value>0&&value<256)
return 1;
return 0;
}
else if(cnt==3)
{
value=ipSeg[0]*100+ipSeg[1]*10+ipSeg[2];
if(value>0&&value<256)
return 1;
return 0;
}
else
return 0;
}

int islegal(char *str)
{
char *p=str;
int ipSeg[3];
int len;
int cnt,i;
char curChar;
for(i=0;i<4;i++)
{
cnt=0;
while(*p!='.'&&*p!='\0')
{
if(cnt>2)
return 0;           //非法
if(isdigit(curChar=*p))
{
ipSeg[cnt]=curChar-'0';
cnt++;
}
else
return 0;
p++;
}
if(!isIn255(ipSeg,cnt))
return 0;               //非法
p++;
}
return 1;
}
int main()
{
char ipStr[16];
int flag;
scanf("%[^\n]",ipStr);
flag=islegal(ipStr);
printf("%s\n",flag==1?"YES":"NO");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: