题解 | #验证IP地址#

验证IP地址

https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 验证IP地址
 * @param IP string字符串 一个IP地址字符串
 * @return string字符串
 */
#include <ctype.h>
#include <string.h>

int str_to_10(char* s,char* e)
{
    if(s == e ||('0'==s[0] && '0' != s[1]))
        return 256;

    int num = 0;
    while(s<e)
    {
        if(!isdigit(*s))
            return 256;
            
        num = num*10 + (*s++ -'0');
    }
    return num;
}

int str_to_16(char* s,char* e)
{
    if(s == e || ('0'==s[0] && '0' == s[1]))
        return 65536;

    int num = 0;
    while(s<e)
    {
        if(!isxdigit(*s))
            return 65536;
        if(isalpha(*s))
            num = num*16 + (*s++ -'0');
        else if(islower(*s))
            num = num*16 + (*s++ -'a');
        else
            num = num*16 + (*s++ -'A');;
    }
    return num;
}

int is_ipv4(char* IP)
{
    char *s = IP, *e = NULL, n = 0;
    while(NULL != (e=strchr(s,'.')))
    {
        if(255 < str_to_10(s,e))
            return 0;
        s = e + 1;
        n++;
    } 

    return !(3 != n || 255 < str_to_10(s,s+strlen(s)));
}

int is_ipv6(char* IP)
{
    char *s = IP, *e = NULL, n = 0;
    while(NULL != (e=strchr(s,':')))
    {
        if(65535 < str_to_16(s,e))
            return 0;
        s = e + 1;
        n++;
    } 

    return !(7 != n || 65535 < str_to_16(s,s+strlen(s)));
}

char* solve(char* IP ) 
{
    // write code here
    if(is_ipv4(IP))
        return "IPv4";
    else if(is_ipv6(IP))
        return "IPv6";
    return "Neither";
}

全部评论

相关推荐

一名愚蠢的人类:多少games小鬼留下了羡慕的泪水
投递荣耀等公司10个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务