您的位置:首页 > 其它

检测ip字符串是否合法

2014-12-29 17:17 183 查看
#include <stdio.h>
#include <string.h>
#include <assert.h>

typedef enum {false, true} bool;

bool checkIsIP_Valid(char *s)
{
assert( s != NULL );

char sec[3];

int num = 3;

int dot_count = 0;

memset(sec, '\0', 3);

while( *s != '\0' )
{
if( *s >= '0' && *s <= '9' )
{
//1234.x.x.x
if( num < 0 )
{
return false;
}
else
{
sec[ 3-num ] = *s;
num--;
}
}
else if( *s == '.' )
{
// .x.x.x
if( num == 3 )
{
return false;
}

//369.x.x.x
if( atoi(sec) > 255 )
{
return false;
}

//fprintf(stderr, "%d.", atoi(sec));
//reset num and sec[]
num = 3;
memset(sec, '\0', 3);

dot_count++;
}
else
{
return false;
}

s++;
}

if( num == 3 || atoi(sec) > 255 || dot_count != 3 )
{
return false;
}
else
{
fprintf(stderr, "\n");
return true;
}
}

//test
char *casen[] = {
"1.2.3.369",
"1.2.369.4",

".2.3.4",
"1.2..4",

"1.2.3",

"a.2.3.4",

"1.2.3.4"
};

int main()
{
int i;

for( i=0; i<7; i++ )
{
fprintf(stderr, "%s is %s\n", casen[i], checkIsIP_Valid( casen[i] ) == true ? "valid" : "invalid");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: