简体   繁体   English

检查IPv4地址是否有效

[英]Checking if an IPv4 address is valid

I am trying to write a basic program in Java that checks if an IP address is valid. 我正在尝试用Java编写一个基本程序,以检查IP地址是否有效。 I am trying to use no external classes other than the Scanner class and also no regular expressions. 我正在尝试不使用除Scanner类之外的任何外部类,也不要使用任何正则表达式。

My code, available at this gist takes in 4 integers as input, one for each octet. 我的代码(在本要点可用)采用4个整数作为输入,每个八位位组一个。 I also have this code which is a little more readable than the first but is longer. 我也有这段代码 ,它比第一个更具可读性,但是更长。

My question is, is there any other way to implement this idea in significantly fewer lines, and if so, how would I accomplish this? 我的问题是,是否还有其他方法可以以更少的行数来实现这个想法,如果是的话,我将如何实现?

While this code segment is a bit verbose, it is simple, self-descriptive, and has proven to be tight. 尽管此代码段有些冗长,但它很简单,具有自描述性,并且被证明是严格的。

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

only some minor enhancements (i think your code looks very good - my opinio so far) it is clearly to read and all work blocks are properly to understand.... 只有一些小的增强(我认为您的代码看起来非常好 -到目前为止,我的观点)可以清楚地阅读并且所有工作块都可以正确理解。

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

so i simply invert the order of printing - that saves you only that big check before... 所以我只是简单地反转打印顺序-这样可以节省您之前的大笔支票...

your approach was to can check each octet... 您的方法是可以检查每个八位位组...

you can simply do this 4 times or write a method for it: 您可以简单地执行4次或编写一个方法:

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

and use this method in your main method 并在您的主要方法中使用此方法

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

note - this only reveals the first invalid octet - if you want to check all you need another boolean 注意-这仅显示第一个无效的八位位组-如果要检查所有内容,则需要另一个布尔值

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

a totally different approach would be to use http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getByName%28java.lang.String%29 完全不同的方法是使用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");
}

but this as well doesn't provide information about that octet which is invalid... 但这也不提供有关该八位字节的信息,这是无效的...

(by the way - what is wrong with your code? it's fine, really!) (顺便说一句-什么你的代码错误很细,真的吗?!)

I was just bored and wrote this 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;
}

And it was tested on the following dataset: 并在以下数据集上进行了测试:

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");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM