如何判断合法的IP地址,尽可能考虑各种情况 (腾讯面试题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hehongonghh/article/details/82663571

static int CountPoint(const char *str)
{
    int count = 0;
    while(*str != '\0')
    {
        if(*str == '.')
            count++;
        str++;
    }
    return count;
}

//判断IPV4的地址是否合法的程序
//只对IP地址如下规则做了判断,其它的同学们可以补充
//IP地址的规则是: (1~255).(0~255).(0~255).(0~255)。例如192.168.2.1
bool IsIP(const char *str)
{
    const char *p = NULL;
    int num = 0;
    if(str == NULL)
    {
        return false;
    }
    if(CountPoint(str) != 3)//IP地址只有3个.号
    {
        return false;
    }
    if(str[0]=='0')//IP地址起始不能为0
    {
        return false;
    }
    while(*str != '\0')
    {
        if(isdigit(*str))
        {
            num = num*10 + *str - '0';
        }
        else if(*str != '.' || num>255)
        {
            return false;
        }
        else
        {
            num = 0;
        }
        str++;
    }
    if(num > 255)//处理尾部数据
        return false;

    return true;
}

int main()
{
    char *str[] = {"192.168.1.1","1.0.0","1.0.0.0","256.1.2.1","192.1.1.256"};
    for(int i=0;i<sizeof(str)/sizeof(str[0]);i++)
    {
        if(IsIP(str[i]))
        {
            printf("%s 是合法的IP\n",str[i]);
        }
        else
        {
            printf("%s 不是合法的IP\n",str[i]);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hehongonghh/article/details/82663571
今日推荐