有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查IPv4地址是否有效

我试图用Java编写一个基本程序,检查IP地址是否有效。除了Scanner类,我尝试不使用任何外部类,也不使用正则表达式

我的代码在this gist上可用,它接受4个整数作为输入,每个八位字节一个。我还有this code,它的可读性比第一个略高,但更长

我的问题是,有没有其他方法可以在更少的行中实现这个想法,如果有,我将如何实现这一点


共 (4) 个答案

  1. # 1 楼答案

    我只是觉得无聊,写了这个regexp

    public static boolean isValid(String ip) {
        boolean isvalid;
    
        isvalid = ip.matches(
                "(([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3}).){3}" +
                 "([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3})"
        );
    
        return isvalid;
    }
    

    并在以下数据集上进行了测试:

    String[] ips = {
            "0.0.0.0",
            "0.111.222.0",
            "0.0.0.000",
            "0.00.0.000",
            "1.1.1.1",
            "2.2.2.2",
            "12.13.14.15",
            "29.29.29.29",
            "99.99.000.1",
            "111.102.144.190",
            "255.255.199.199",
            "266.255.255.255", //inv
            "255.265.255.255", //inv 
            "255.255.258.255", //inv 
            "255.255.255.259", //inv 
            "299.100.110.255" //inv
        };
        for (String s : ips) {
            if (isValid(s) == false) {
                System.err.println(s + " is invalid");
            }
        }
    
  2. # 2 楼答案

    你的方法是检查每个八位组

    您可以简单地执行4次,或为此编写一个方法:

    private static boolean check(int octet, int index){
        if (0xFF & octet < 256) return true;
        System.out.println("Octet "+index+" is invalid";
        return false;
    }
    

    并在主方法中使用此方法

    if (check(first,0) && check (second, 2) && check (third, 3) && check(fourth, 4) ){
        System.out.println("your ip is valid");
    }
    

    注意-这只显示第一个无效的八位字节-如果要检查所有内容,需要另一个布尔值

    boolean result = check(first,0) && 
        check (second, 2) && 
        check (third, 3) && 
        check(fourth, 4); //reveals all errors
    

    一种完全不同的方法是使用http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getByName%28java.lang.String%29

    try{
        /*InetAdress adress =*/ InetAdress.
            getByName(""+first+"."+second+"."+third+"."+forth)
        System.out.println("your ip is valid");
    }catch (UnknownHostException e){
        //TODO represent that error message into a nice expression
        System.out.println("your ip is invalid");
    }
    

    但是这也没有提供关于八位组的信息,这是无效的

    (顺便问一下,你的代码有什么问题吗?真的很好!)

  3. # 3 楼答案

    虽然这个代码段有点冗长,但它简单、自描述性,并且已经被证明是紧凑的

    private static boolean isIPAddressValid(String ip) {    
        boolean result = true;
        int i = 0;
        int [] val = new int[4];
    
        if ((ip == null) || (ip.trim().length() == 0))
        {
            //null ip address entered
            result = false;
        }
        else
        {
            if (!(ip.contains(".")))
            {
                //no '.' found
                result = false;
            }
            else
            {
                String [] parts = ip.split("\\.");
                if (!(parts.length == 4))
                {
                    //not 4 quadrants
                    result = false;
                }
                else
                {
                    for (String s : parts) { 
                        try {
                            val[i] = Integer.parseInt(s);
                            if ((val[i] < 0) || (val[i] > 255))
                            {
                                //this quadrant's value exceeds limits
                                result = false;
                            }
                            i++;
                        } catch (Exception e) {
                            //failed to parse quadrant to an integer");
                            result = false;
                        }
                    }
                }
            }
        }
        return result;
    }
    
  4. # 4 楼答案

    只有一些小的改进(我认为你的代码看起来很好,到目前为止,我的观点是),它很容易阅读,所有的工作块都很容易理解

    boolean isFailed = false;
    if (first < 0 || first > 255) {
        System.out.println("Octet 1 is invalid");
        isFailed = true;
    }
    if (second < 0 || second > 255) {
        System.out.println("Octet 2 is invalid");
        isFailed = true;
    }
    if (third < 0 || third > 255) {
        System.out.println("Octet 3 is invalid");
        isFailed = true;
    }
    if (fourth < 0 || fourth > 255) {
        System.out.println("Octet 4 is invalid");
        isFailed = true;
    }
    
    if (!isFailed){
        System.out.println("IP Address: " + first + "." + second + "." + third + "." + fourth);
    }
    

    所以我简单地颠倒了打印的顺序-这只为您节省了之前的检查