现在的位置: 首页 > 综合 > 正文

[转]VC鉴别IP是否规范

2013年09月17日 ⁄ 综合 ⁄ 共 844字 ⁄ 字号 评论关闭
原文自 http://blog.csdn.net/ccrazyman/article/details/8038111,看到这段代码很好,就转过来了。
对原文有改动和增加。
本代码在VC6下编译运行成功!
注意事项写在前面:
1.该代码未添加main函数和头文件,该函数无需头文件,只要你添加主函数和
        #define NULL 0
   即可。
2.调用函数时,这个函数的实参一定要是char型数组,不能用char*代替。
  例如:
  char* ip;
  check_ip(ip);
  这是错误的,我也不知道为什么,运行时反正会出现内存错误的提示
  应该这样:
  char ip[16];
  check_ip(ip);
  这样就没问题了。
函数源码:
int check_ip(char *ip)
{
    char * p=ip;
    int count=0;
while(*p != '\0')
    {
        if( *p == '.')
            count++;
        p++;
    }
    if( count != 3 )
        return false;
p=ip;
for(int i=0;i<4;++i)
     {
int len=0;
int tem=0;
while(*p!=NULL)
         {
if(*p=='.')
                   break;
tem=tem*10+*p-'0';
p++;
len++;
          }
  if(len==1)
          {
                 if(tem<0||tem>9)
                     return false;
}
          else if(len==2)
         {
if(tem<10 ||tem>99)
                    return false;
  }
         else if(len==3)
         {
if(tem<100||tem>255)
                     return false;
         }
         else 
             return false;
        if(*p!='\0')
            p++;
}
return true;
}

抱歉!评论已关闭.