#include <iostream>
#include <algorithm>
using namespace std;

class Solution
{
public:
    string validIPAddress(string IP)
    {
        //以.和:来区分ipv4和ipv6
        for (int i = 0; i < IP.length(); i++)
        {
            if (IP[i] == '.')
                return isIPv4(IP) ? "IPv4" : "Neither";
            else if (IP[i] == ':')
                return isIPv6(IP) ? "IPv6" : "Neither";
        }
        return "Neither";
    }
private:
    bool isIPv4(string IP)
    {
        int dotcnt = 0;
        //数一共有几个.
        for (int i = 0; i < IP.length(); i++)
        {
            if (IP[i] == '.')
                dotcnt++;
        }
        //ipv4地址一定有3个点
        if (dotcnt != 3)
            return false;
        string temp = "";
        for (int i = 0; i < IP.length(); i++)
        {
            if (IP[i] != '.')
                temp += IP[i];
            //被.分割的每部分一定是数字0-255的数字
            if (IP[i] == '.' || i == IP.length() - 1)
            {
                if (temp.length() == 0 || temp.length() > 3)
                    return false;
                for (int j = 0; j < temp.length(); j++)
                {
                    if (!isdigit(temp[j]))
                        return false;
                }
                int tempInt = stoi(temp);
                if (tempInt > 255 || tempInt < 0)
                    return false;
                string convertString = to_string(tempInt);
                if (convertString != temp)
                    return false;
                temp = "";
            }
        }
        if (IP[IP.length()-1] == '.')
            return false;
        return true;
    }
    bool isIPv6(string IP) {
        int dotcnt = 0;
        for (int i = 0; i < IP.length(); i++)
        {
            if(IP[i] == ':')
                dotcnt++;
        }
        if (dotcnt != 7) return false;
        string temp = "";
        for (int i = 0; i < IP.length(); i++)
        {
            if (IP[i] != ':')
                temp += IP[i];
            if (IP[i] == ':' || i == IP.length() - 1)
            {
                if (temp.length() == 0 || temp.length() > 4)
                    return false;
                for (int j = 0; j < temp.length(); j++)
                {
                    if (!(isdigit(temp[j]) ||(temp[j] >= 'a' && temp[j] <= 'f') || (temp[j] >= 'A' && temp[j] <= 'F')))
                        return false;
                }
                temp = "";
            }
        }
        if (IP[IP.length()-1] == ':')
            return false;
        return true;
    }
};

int main()
{
    Solution sol;
    string s;
    cin >> s;
    cout << sol.validIPAddress(s);
    return 0;
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐