c/c++——判断一个字符串是否为合法IP地址(包括IPV4和IPV6)

#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;
}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值