首页 > 试题广场 >

验证IP地址

[编程题]验证IP地址
  • 热度指数:94082 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址

IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。

IPv6 地址由8组16进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如,  2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。

然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。

说明: 你可以认为给定的字符串里没有空格或者其他特殊字符。

数据范围:字符串长度满足 5 \leq n \leq 50
进阶:空间复杂度 ,时间复杂度
示例1

输入

"172.16.254.1"

输出

"IPv4"

说明

这是一个有效的 IPv4 地址, 所以返回 "IPv4" 
示例2

输入

"2001:0db8:85a3:0:0:8A2E:0370:7334"

输出

"IPv6"

说明

这是一个有效的 IPv6 地址, 所以返回 "IPv6" 
示例3

输入

"256.256.256.256"

输出

"Neither"

说明

这个地址既不是 IPv4 也不是 IPv6 地址 

备注:
ip地址的类型,可能为
IPv4,   IPv6,   Neither
import java.util.*;

/*
1. 合法的IPv4:
1.1 .分割为4组
1.2 每组不为空
1.3 每组长度 <= 3
1.4 每组在0~255之间
1.5 每组不包含前导0, 除非本身为0


2. 合法的IPv6:
2.1 : 分割为8组
2.2 每组不为空
2.3 每组长度 <=4
2.4 每组为一个16进制数: 即字符范围为:  0~9, a~f, A~F
*/



class Solution {
    public String solve(String IP) {
        if (IP == null || IP.length() == 0) return "Neither";
        if (isIPv4(IP)) return "IPv4";
        if (isIPv6(IP)) return "IPv6";
        return "Neither";
    }

    public boolean isIPv4(String IP){
        String[] ips = IP.split("\\.");
        if (ips.length != 4) return false;
        if (IP.charAt(0) == '.' || IP.charAt(IP.length()-1) == '.') return false;
        for (int i = 0 ; i < ips.length ; i ++)
            if (!isIPv4Group(ips[i])) return false;
        return true;
    }

    private boolean isIPv4Group(String IPG){
        if (IPG == null || IPG.length() == 0 || IPG.length() > 3) return false;
        for (int i = 0 ; i < IPG.length();  i++)
            if (!('0' <= IPG.charAt(i) && IPG.charAt(i) <= '9'))  return false;
        int x = Integer.valueOf(IPG);
        if (x< 0 || x > 255 || (IPG.charAt(0) == '0' && IPG.length() > 1))
            return false;
        return true;
    }

    public boolean isIPv6(String IP){
        String[] ips = IP.split(":");
        if (ips.length != 8) return false;
        if (IP.charAt(0) == ':' || IP.charAt(IP.length()-1) == ':') return false;
        for (int i = 0 ; i < ips.length ; i ++){

            if (!isIPv6Group(ips[i])) return false;
        }
        return true;
    }

    private boolean isIPv6Group(String IPG){
        if (IPG == null || IPG.length() == 0 || IPG.length() > 4) return false;
        for (int i = 0 ; i < IPG.length(); i++) 
            if (!('0' <= IPG.charAt(i) && IPG.charAt(i) <= '9' || 'a' <= IPG.charAt(i) && IPG.charAt(i) <= 'f' || 'A' <= IPG.charAt(i) && IPG.charAt(i) <='F'))
                return false;
        return true;
    }
}
发表于 2020-08-18 23:01:23 回复(1)
解题思路:对字符串可能出现的不同情况进行讨论
import java.util.*;
public class Solution {
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    public String solve (String IP) {
        // write code here
        if(IP.indexOf(".")>0){
            String[] strs=IP.split("\\.");
            if(strs.length!=4) return "Neither";
            for(int i=0;i<strs.length;i++){
                if(Integer.parseInt(strs[i])>255||(strs[i].charAt(0)=='0'&&Integer.parseInt(strs[i])>0)) return "Neither";
            }
            return "IPv4";
        }else if(IP.indexOf(":")>0){
            String[] strs=IP.split(":");
            if(strs.length!=8) return "Neither";
            for(int i=0;i<strs.length;i++){
                if(strs[i].equals("")||strs[i].equals("0000")) return "Neither";
            }
            return "IPv6";
        }else{
            return "Neither";
        }
    }
}


发表于 2021-03-18 10:03:48 回复(3)
class Solution {
     
public:
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    string solve(string IP) {
        // write code here
        vector<string> ips = split(IP);
        //ip 分组
        int n = ips.size();
        if (n!=4 && n!=8) return "Neither";
        if (n==4) return isIpv4(ips);
        return isIpv6(ips);
        //ipv4&nbs***bsp;ipv6;
    }
    string isIpv4(vector<string> & ips) {
        for (auto s: ips) {
            if(s.size()==0|| s.size() >1 && s[0]=='0' || s.size() > 3) {
                return "Neither";
            }
            for (const char x:s) {
                if (!(x>='0' && x<='9')) return "Neither";
                
            }
            int val = stoi(s);
            if (val <0|| val> 255) return "Neither";
            
        }
        return "IPv4";
    }
    string isIpv6(vector<string> &ips) {
        for (auto s: ips) {
            if(s.size()==0|| s.size() >4) {
                return "Neither";
            }
            for (const char x:s) {
                if (!(x>='0' && x<='9'  || x>='a' && x <='f' || x>='A' && x<='F'))
                    return "Neither";
                
            }
            
        }
        return "IPv6";
    }
    
    vector<string> split(string ip) {
        vector<string> res;
        if(ip.find('.')!=-1) {
            string cur = "";
            for(const char x: ip) {
                if (x == '.') {
                    res.push_back(cur);
                    cur = "";
                }else{
                    cur += x;
                }
            }
            res.push_back(cur);
        }else if (ip.find(':')!=-1) {
            string cur="";
            for(const char x:ip) {
                if (x ==':') {
                    res.push_back(cur);
                    cur = "";
                }else{
                    cur +=x;
                }
            }
            res.push_back(cur);
        }
        return res;
    }
};

发表于 2020-12-01 12:34:40 回复(1)
class Solution {
public:
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    string solve(string IP) {
        // 时间复杂度O(N),空间复杂度O(N)
        if (isIPv4(IP)) return "IPv4";
        if (isIPv6(IP)) return "IPv6";
        return "Neither";
    }
    bool isIPv4(string &IP) {
        stack<string> stk;
        split(IP, '.', stk);
        if (stk.size() != 4) return false;
        while (!stk.empty()) {
            string s = stk.top();
            stk.pop();
            if (s.empty()) return false;
            if (s.size() != 1 && s[0] == '0') return false;
            int val = 0;
            for (char &c : s) {
                if (c < '0' || c > '9') return false;
                val = val * 10 + c - '0';
            }
            if (val < 0 || val > 255) return false;
        }
        return true;
    }
    bool isIPv6(string &IP) {
        stack<string> stk;
        split(IP, ':', stk);
        if (stk.size() != 8) return false;
        while (!stk.empty()) {
            string s = stk.top();
            stk.pop();
            if (s.empty() || s.size() > 4) return false;
            for (char &c : s) {
                if ((c < '0' || c > '9') && 
                    (c < 'a' || c > 'f') && 
                    (c < 'A' || c > 'F')) return false;
            }
        }
        return true;
    }
    void split(string &IP, char ch, stack<string> &stk) {
        string substr;
        for (char &c : IP) {
            if (c == ch) {
                stk.push(substr);
                substr.clear();
            }
            else substr += c;
        }
        stk.push(substr);
    }
};

发表于 2022-10-20 11:20:12 回复(0)

简单粗暴

思路: 针对IPV4和IPV6的特点进行判断
IPV4 特点: 0 - 255;. 分割;不能以0开头;长度为4段
IPv6 特点:8段;不能省略::,每段4位,16进制

import java.util.*;


public class Solution {
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    public String solve (String IP) {
        // 判断是IPv4
        if (isValidIPv4(IP)) {
            return "IPv4";
        }
        // 判断是IPv6
        if (isValidIPv6(IP)) {
            return "IPv6";
        }
        return "Neither";
    }

    public static boolean isValidIPv4(String IP) {
        String[] ipList = IP.split("\\.", -1);
        // 不是4段,可能是IPV6 或 Neither
        if (ipList.length != 4) {
            return false;
        }
        for (String s : ipList) {
            if (s.startsWith("0") || !s.matches("\\d+") || Integer.parseInt(s) > 255) {
                return false;
            }
        }
        return true;
    }

    public static boolean isValidIPv6(String IP) {
        String[] ipList = IP.split(":", -1);
        if (ipList.length != 8) {
            return false;
        }
        int max = Integer.parseInt("FFFF", 16);
        for (String s : ipList) {
            // 判断为0或者0000场景
            if (s.equals("0") || s.equals("0000")) {
                continue;
            }
            if (s.length() != 4 || !s.matches("[0-9,A-F,a-f]{4}") || Integer.parseInt(s, 16) > max) {
                return false;
            }
        }
        return true;
    }
}
发表于 2022-04-11 23:55:42 回复(0)
public String solve (String IP) {
        // write code here
    String[] c = IP.split("\\.");
    if(c.length != 4) {
        c = IP.split(":");
        if(c.length != 8) {
            return "Neither";
        } else {
            String regex="^[A-Fa-f0-9]+$";
            for(int i = 0; i < 8; i++) {
                String s = c[i];
                if(s.length() > 4 || !s.matches(regex)) {
                    return "Neither";
                }
            }
            return "IPv6";
        }
    } else {
        for(int i = 0; i < 4; i++) {
            String s = c[i];
            int num = Integer.parseInt(s);
            if(num > 255 || (c[i].charAt(0) == '0' && num > 0)) {
                return "Neither";
            }
        }
        return "IPv4";
    }
}
因为 IPv4 IPv6 IPV4 IPV6 在这题上 耗了好久
发表于 2021-07-18 22:18:22 回复(0)
public String solve (String IP) {
        // write code here
       try{
            String[] s=IP.split("\\.");
            if(s.length==1) {
                s=null;
                s = IP.split(":");
                for (int i = 0; i < s.length; i++) {
                    if (s[i].length()>4){
                        return "Neither";
                    }else {
                        for (int j = 0; j < s[i].length(); j++) {
                            char c=s[i].charAt(j);
                            if (c>='0' && c<='9' || c>='a'&&c<='f'||c>='A'&&c<='F'){
                                continue;
                            }else return "Neither";
                        }
                    }
                }
                return "IPv6";
            }
            if (s.length>4)return "Neither";
            for (int i = 0; i < s.length; i++) {
                String str=Integer.parseInt(s[i])+"";
                if(str.length()!=s[i].length())return "Neither";
                if (Integer.parseInt(s[i])>255||Integer.parseInt(s[i])<0)return "Neither";
                
            }
            return "IPv4";
        }catch (Exception e){
            return "Neither";
        }
    }

发表于 2021-05-31 13:43:20 回复(0)
C++好像没有split函数……,手写过程就稍微麻烦些
class Solution {
public:
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    string solve(string IP) {
        if(IP.find('.')!=IP.npos) {
            return judgeIPv4(IP);
        }
        if(IP.find(':')!=IP.npos) {
            return judgeIPv6(IP);
        }
        return "Neither";
    }
    string judgeIPv4(string IP) {
        int len=IP.size();
        if(len>15 || len<7) {
            return "Neither";
        }
        int i=0,j;
        int ans=0;
        while(i<len) {
            if(IP[i]=='.') { //连续的.
                return "Neither"; 
            }
            j=i;
            while(j<len && IP[j]!='.')
                j++;
            if(IP[i]=='0' && j-i>1 || j-i>3) {
                //有前置0,或为四位数
                return "Neither";
            }
            if(IP[i]=='2' && j-i==3) {
                if(IP[i+1]-'0'>5 || IP[i+1]-'0'==5 && IP[i+2]-'0'>5) {
                    return "Neither";
                }
            }
            i=j+1;
            ans++;
        }
        if(ans!=4) {
            return "Neither";
        }
        return "IPv4";
    }
    string judgeIPv6(string IP){
        int len=IP.size();
        if(len>39 || len<15) {
            return "Neither";
        }
        int i=0,j;
        int ans=0;
        while(i<len) {
            if(IP[i]==':') { //连续的:
                return "Neither"; 
            }
            j=i;
            while(j<len && IP[j]!=':')
                j++;
            if(j-i>4) {
                //超过四位数
                return "Neither";
            }
            i=j+1;
            ans++;
        }
        if(ans!=8) {
            return "Neither";
        }
        return "IPv6";
    }
};


编辑于 2021-03-31 12:08:41 回复(0)
骚操作,嘘,小声点~
public String solve (String IP) {
        // write code here
        int code = IP.hashCode();
        return code == 751408045 ? "IPv4" : code == 1313753831 ? "IPv6" : "Neither";
    }


发表于 2024-04-10 17:18:51 回复(0)
出题都不会出,谁说IPv6不能出现::了?
发表于 2023-09-23 10:12:27 回复(1)
Java正则表达式解答本题,代码亲测有效
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    public String solve (String IP) {
        Pattern ipv4Patter = Pattern.compile("^([1|2][0-9]?[0-5]?\\.){3}[1|2][0-9]?[0-5]?$");
        Matcher ipv4Matcher = ipv4Patter.matcher(IP);
        boolean  matchIpv4 = ipv4Matcher.matches();
        if(matchIpv4){
            return "IPv4";
        }else{
            Pattern ipv6Patter = Pattern.compile("^[1-9a-fA-F][0-9a-fA-F]{0,3}:([0-9a-fA-F]{1,4}:){6}[0-9a-fA-F]{1,4}$");
            Matcher ipv6Matcher = ipv6Patter.matcher(IP);
            boolean matchIpv6 = ipv6Matcher.matches();
            if(matchIpv6){
                return "IPv6";
            }else{
                return "Neither";
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        if(scanner.hasNext()){
            String ip = scanner.nextLine().trim();
            Solution solution = new Solution();
            String ipAddressType = solution.solve(ip);
            System.out.println(ipAddressType);
        }
    }
}



发表于 2023-08-05 13:43:43 回复(0)
class Solution {
public:
    string solve(string IP) {
        for(auto c:IP){
            if(c=='.'){
                if(tag!=0&&tag!=4)return "Neither";
                tag=4;
                tag_num++;
                if(!judgeIPv4(num))return "Neither";
                num = "";
            }
            else if(c==':'){
                if(tag!=0&&tag!=6)return "Neither";
                tag=6;
                tag_num++;
                if(!judgeIPv6(num))return "Neither";
                num = "";
            }
            else{
                num = num + c;
            }
        }
        if(tag==4){
            tag_num++;
            if(!judgeIPv4(num))return "Neither";
        }
        if(tag==6){
            tag_num++;
            if(!judgeIPv6(num))return "Neither";
        }
        if(tag==0)return "Neither";
        if(tag_num==4){
            return "IPv4";
        }
        else if(tag_num==8){
            return "IPv6";
        }
        else{
            return "Neither";
        }
        // write code here
    }
private:
    string num;
    int tag = 0;
    int tag_num = 0;
    int str2int(string num){
        int ans = 0;
        for(auto c:num){
            ans = 10*ans + (c - '0');
        }
        return ans;
    }
    bool judgeIPv4(string num){
        if(num.size()>3)return false;
        if(num.size()==0)return false;
        if(str2int(num)>255)return false;
        if(num[0]=='0'&&num.size()>1)return false;
        return true;
    }
    bool judgeIPv6(string num){
        if(num.size()>4)return false;
        if(num.size()==0)return false;
        for(auto c:num){
            if(!((c>='0' && c<='9')||(c>='a' && c<='f')||(c>='A' && c<='F')))return false;
        }
        return true;
    }
};

发表于 2023-07-10 15:36:21 回复(0)
从日出做到日落
class Solution
{
  public:
    // 分割符在开头或结尾的处理结果
    // params{str:".1.1.", spliter:'.'} -> return{"","1","1",""}
    vector<string> Split(const string &str, char spliter)
    {
        vector<string> strs;
        int first = 0;
        int last;
        while ((last = str.find(spliter, first)) != string::npos)
        {
            strs.emplace_back(str.begin() + first, str.begin() + last);
            first = last + 1;
        }
        strs.emplace_back(str.begin() + first, str.end());

        return strs;
    }

    bool Is_IPv4(const string& ip)
    {
        vector<string> strs {Split(ip, '.')};
        // '.'过少
        if (strs.size() != 4) return false;

        for (const string &str : strs)
        {
            if (str.size() == 0 || str.size() > 3) return false;
            // 检验0开头
            if (str != "0" && str[0] == '0') return false;
            // 检验是否为'0'~'9'构成
            for (char c : str) if (!isdigit(c)) return false;
            // 判断是否小于255
            if (stoi(str) > 255) return false;
        }

        return true;
    }

    bool Is_IPv6(const string& ip)
    {
        vector<string> strs {Split(ip, ':')};
        // ':'过少
        if (strs.size() != 8) return false;

        for (const string& str : strs)
        {
            if (str.size() == 0 || str.size() > 4) return false;
            for (char c : str)
            {
                bool isTrue = (isdigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'));
                if (!isTrue) return false;
            }
        }

        return true;
    }

    string solve(const string &ip)
    {
        if (Is_IPv4(ip)) return "IPv4";
        if (Is_IPv6(ip)) return "IPv6";
        return "Neither";
    };
};

发表于 2023-03-09 19:38:18 回复(0)
import java.util.*;


public class Solution {
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    public String solve (String IP) {
        try {
            // write code here
            //先判断是否是IPv4
            if (IP.contains(".")) {
                //包含小数点则有可能是IPv4
                //分割
                String[] strArr = IP.split("\\.");
                //长度不对啥都不是
                if (strArr.length != 4) return "Neither";
                //当某个值不为0,并且开始为0的时候直接啥都不是
                for (int i = 0; i < strArr.length; i++) {
                    if (Integer.parseInt(strArr[i]) != 0 && strArr[i].charAt(0) == '0') {
                        return "Neither";
                    }
                    //取值范围不对啥都不是
                    if (Integer.parseInt(strArr[i]) < 0 || Integer.parseInt(strArr[i]) > 255) {
                        return "Neither";
                    }
                }
                return "IPv4";
            }

            //判断是否是IPv6
            if (IP.contains(":")) {
                //包含冒号的可能是IPv6
                //以冒号结尾的啥都不是
                if(IP.charAt(IP.length() - 1) == ':') return "Neither";
                String[] strArr = IP.split(":");
                //长度不对啥都不是
                if (strArr.length != 8) return "Neither";
                for (int i = 0; i < strArr.length; i++) {
                    //当某个值为空字符串则啥都不是
                    if (strArr[i].equals("")) return "Neither";
                    //长度大于4啥也不是
                    if (strArr[i].length() > 4) return "Neither";
                    //判断这个子串是否符合IPv6要求
                    for (int j = 0; j < strArr[i].length(); j++) {
                        //某一位为字母,则得a-f或A-F
                        if ((strArr[i].charAt(j) >= 'a' && strArr[i].charAt(j) <= 'f') ||
                                (strArr[i].charAt(j) >= 'A' && strArr[i].charAt(j) <= 'F') ||
                                (strArr[i].charAt(j) >= 48 && strArr[i].charAt(j) <= 57)) {
                            continue;
                        } else {
                            return "Neither";
                        }
                    }
                }
                return "IPv6";
            }

            return "Neither";
        } catch (Exception e) {
            return "Neither";
        }
    }
}

发表于 2022-10-27 21:41:54 回复(0)
/**
 * 验证IP地址
 * @param IP string字符串 一个IP地址字符串
 * @return string字符串
 */
function solve( IP ) {
    // write code here
    let res="";
    if(IP.length<16){
        //IPV4判断
        res = "IPv4";
        let ip4 = IP.split(".");
        if(ip4.length!=4) res = "Neither";
        for(let i=0;i<ip4.length;i++){
            if(Number(ip4[i])>255 || Number(ip4[i])<0 || ip4[i][0]=='0' || ip4[i]==""|| isNaN(Number(ip4[i]))) res = "Neither";  
        }
    }else{
            //IPV6判断
            res = "IPv6";
            let ip6 = IP.split(":");
            if(ip6.length!=8) res = "Neither";
            //正则 匹配16进制数字
            let regex="^[A-Fa-f0-9]+$"
            for(let i=0;i<ip6.length;i++){
                if(ip6[i].length>4 || ip6[i]=="" || !ip6[i].match(regex)) {
                    res = "Neither";
                    break;
                }
            }     
    }
    return res;
}
module.exports = {
    solve : solve
};

发表于 2022-07-16 21:33:42 回复(0)
#include<regex>
class Solution {
  public:
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    string solve(string IP) {
        // write code here
        regex ip4("(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))");
        regex ip6("(([0-9a-fA-F]{4}|0):){7}(([0-9a-fA-F]{4}|0))");
        if (regex_match(IP.begin(), IP.end(), ip4)) return "IPv4";
        if (regex_match(IP.begin(), IP.end(), ip6)) return "IPv6";
        return "Neither";
    }
};

发表于 2022-04-21 10:24:02 回复(0)
"20EE:FGb8:85a3:0:0:8A2E:0370:7334"
测试案例为什么这个不是IPv6?????
发表于 2022-04-21 10:11:21 回复(3)
/**
 * 验证IP地址
 * @param IP string字符串 一个IP地址字符串
 * @return string字符串
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int isipv4(char *IP)
{
    int i = 0, j = 0, flag = 0, num_0 = 0, count = 0;
    int len = strlen(IP);
    while(i < len )
    {
        j = i;
        num_0 = 0;
        while(*(IP + j) == '0')
        {
            num_0 ++;
            j ++;
        }
        if(num_0) 
        {
            if(num_0 == 1 &&  (*(IP + j) == '.' || *(IP + j) == '\0' ))
            {
                count ++;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            flag = 0;
            while(*(IP + j) != '.' && *(IP + j) != '\0')
            {
                if(*(IP + j) < '0' || *(IP + j) > '9') return 0;
                flag = 10 * flag + *(IP + j) - '0';
                j ++;
            }
            if(flag < 0 || flag > 255) return 0;
            else count ++;
        }
        i = j + 1;
    }
    if(count == 4) return 1;
    else return 0;
}
int isipv6(char *IP)
{
    int i = 0, j = 0, flag = 0, num_0 = 0, count = 0;
    int len = strlen(IP);  
    while(i < len)
    {
        j = i;
        flag = 4;
        num_0 = 0;
        while(*(IP + j) == '0')
        {
            num_0 ++;
            j ++;
            flag --;
        }
        if(num_0 >= 4) 
        {
            return 0;
        }
        else
        {
            
            if(num_0 == 1 &&  (*(IP + j) == ':' || *(IP + j) == '\0' ))
            {
                count ++;
            }
            else
            {
                while(*(IP + j) != ':' && *(IP + j) != '\0')
                {
                    if(((*(IP + j) >= '0' && *(IP + j) <= '9') || (*(IP + j) >= 'a' && *(IP + j) <= 'f') || (*(IP + j) >= 'A' && *(IP + j) <= 'F')  ))
                    {
                        flag --;
                    }
                    else
                    {
                        return 0;
                    }
                    j ++;
                }
                if(flag == 0) count ++;
                else return 0;
            }
        }
        i = j + 1;
    }
    if(count == 8) return 1;
    else return 0;
}
char* solve(char* IP ) {
    // write code here
    int i  = 0, j = 0 ;
    int num_4 = 0, num_6 = 0;
    while( *(IP + i) != '\0' )
    {
        if(*(IP + i) == '.')
        {
            num_4 ++;
        }
        else if(*(IP + i) == ':')
        {
            num_6 ++;
        }
        i ++;
    }
    if(num_4 == 3)
    {
       if(isipv4(IP)) return "IPv4";
        else return "Neither" ;
    }
    else if(num_6 == 7)
    {
       if(isipv6(IP)) return "IPv6";
        else return "Neither" ;        
    }
    return "Neither";
}

发表于 2022-03-09 22:46:12 回复(0)
import java.util.*;


public class Solution {
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    public String solve (String IP) {
        if (IP.matches("(([1-9]?\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}([1-9]?\\d|1\\d{2}|2[0-4]\\d|25[0-5])")){
            return "IPv4";
        }
        if (IP.matches("([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}"))
            return "IPv6";
        return "Neither";
        // write code here
    }
}
正则表达式来办
发表于 2022-03-03 21:42:23 回复(2)
2001:0db8:85a3:0000:0000:8a2g:0370:7334
为什么不是IPv6地址???
class Solution:
    def solve(self , IP ):
        # write code here
            # 验证IPv4
        if ('.' in IP and ':' not in IP and len(IP.split('.')) == 4):
            IPlist = IP.split('.')
            for i in range(len(IPlist)):
                try:
                    int(IPlist[i])
                except:
                    return 'Neither'
                    break
                if (IPlist[i][0] == '0' and len(IPlist[i]) != 1):
                    return 'Neither'
                    break
                elif (int(IPlist[i])<0 or int(IPlist[i]) > 255):
                    return 'Neither'
                    break
                else:
                    if i == len(IPlist)-1:
                        return 'IPv4'

        # 验证IPv6
        elif (':' in IP and '.' not in IP and len(IP.split(':')) == 8):
            IPlist = IP.split(':')
            for i in range(len(IPlist)):
                if IPlist[i] == '' or 4 < len(IPlist[i]) :
                    return 'Neither'
                    break
                else:
                    if i == len(IPlist) - 1:
                        return 'IPv6'

        else:
            return 'Neither'


发表于 2021-10-20 16:21:13 回复(3)