以下代码,其中函数int TESTFUN(char *ipaddr)是判断字符串ipaddr是否为IP地址。
#include "stdio.h"
#include "stdlib.h"
int TESTFUN(char *ipaddr)
{
char *pnum,*pdot=ipaddr;
for(;*ipaddr;ipaddr=pdot++)
{
int t=0,e=1;
if(*(pnum=pdot)=='.')return 0;
for(; *pdot!='.'&&*pdot; ++pdot);
for(ipaddr=pdot-1;ipaddr>=pnum;t+=e*(*ipaddr---'0'),e*=10);
if(t<0||t>255||(pdot-pnum==3&&t<100)||(pdot-pnum==2&&t<10))
return 0;
}
return 1;
}
int main()
{
char * ip[]={
"0.0.0.0",
"255.255.255.255",
"1.2.3.5",
"0.255.0.255",
"00.11.22.33",
"2147483657.1.2.3",
".2.ab.12.4",
"1.02.3.5",
"5..1.1",
"255.256.1.1",
"2.3.6.5.",
"56,41.154.5",
"1.2.3.4.5"
};
int size=sizeof(ip)/sizeof(ip[0]);
while(--size>=0)
{
if( TESTFUN(ip[size]) )
printf("legal %s\n",ip[size]);
else
printf("unlegal %s\n",ip[size]);
}
return 0;
}
阅读(4143) | 评论(0) | 转发(0) |