- 论坛徽章:
- 0
|
有没有那个函数能够检测一个字符串是不是一个合法的IP地址??
以下是我的代码,昨天晚上用了40多分钟才搞定
/*
//Summary: this is to test the IP_check() function which is to check the regulation of IP
//$Id: IP_check_test.c,v 1.2 2005/09/20 04:16:37 $
*/
#include <string.h>;
#include <stdio.h>;
#include <stdlib.h>;
int IP_check(char* chInput, int iLen) // return 1 is to show that chInput is a correct IP, or 0 not a IP
{
int i=0;
int i0=0;
int i1=0;
int iR=0;
char chIP[4][5]={0};
if (strchr(chInput, '.')==NULL)
return 0;
if (iLen>;15)
return 0; //not a IP
if (iLen<7)
return 0;
for(i=0; i<iLen; i++)
{
if (i==0 && chInput=='.')
return 0;
if (chInput=='.')
{
i1++;
iR=iR+strlen(chIP[i1-1])+1;
continue;
}
if (i1==0)
{
if (i>;2)
return 0;
chIP[i1]=chInput;
}
else
{
if ((i-iR)>;2)
return 0;
chIP[i1][i-iR]=chInput;
}
}
if (i1!=3)
return 0;
for(i=0; i<4; i++)
{
if (atoi(chIP)>;=0 && atoi(chIP)<255)
;
else
return 0;
}
return 1;
}
int main(int argc, char* argv[])
{
int ret=0;
ret=IP_check(argv[1], strlen(argv[1]));
if (ret==0)
printf("not a IP\n"
if (ret==1)
printf("is a correct IP\n"
return 0;
} |
|