判断一个ip地址合法性(基础c,不用库函数)

#include <stdio.h>
int judge(char *strIp);
int main()
{
    char a[20];
    while(1)
    {
        scanf("%s", a);
        if(0 == judge(a))
        {
            printf("this is a correct ip
");
        }
    }
}

int judge(char *strIp)
{
   if(NULL == strIp)
   {
      return -1;
   }
//IP must start with 0-9 if(*strIp > '9' || *strIp < '0') { return -1; } int num = 0; int dotNum = 0; do { if(*strIp >= '0' && *strIp <= '9') { num = 10 * num + *strIp - '0'; } else if(('.' == *strIp) || ('' == *strIp)) { //filter the string including '..' or ending with '.' if('.' == *(strIp - 1)) { return -1; } //filter the section number large than 255 or little than 0 if(num < 0 || num > 255) { return -1; } num = 0; //record the number of right dots if('.' == *strIp) { dotNum++; } } else { //Can't have chars excluding '0' - '9' and '.' return -1; } }while(*(strIp++)) if(3 == dotNum) { // ip is correct return 0; } else { //the string is too short for ip return -1; } }
原文地址:https://www.cnblogs.com/penghuster/p/6366791.html