简体   繁体   中英

Java - Throwing an exception if user entered invalid IP address or host name

I want to throw an exception that when a user enters an invalid IP address, host name or not a fully qualified domain name it'll bring up an error message.

I'm not too sure whether to use unknownhostexception or IOException.

I tried doing if statement but I don't know what 'invalid' can be in java.

If (addr != ' not a valid IP address, host name, fully qualified domain name or entered something invalid ')
{
throw new IOException/UnknownHostException("this is invalid: " + addr); }

Can anyone help please? Thanks in advance.

Try InetAddress.getByName(str) to validate the string. It will throw an UnknownHostException if necessary. I suggest removing your if statement entirely. Perhaps something like this:

public static InetAddress testAddress(String str) throws UnknownHostException {
    InetAddress add = InetAddress.getByName(str);

    // Check if IP address was simply returned, instead of host.
    if (add.getCanonicalHostName().equals(add.getHostAddress())) {
        throw new UnknownHostException(str + "is not a known host.");
    }
    return add;
}

There is a concept, called regex (regular expression) where you can check if that pattern is correct. You may have to search for good solutions or write your own regex (which is not so easy in my personal opinion). But here is a good starting point http://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/ ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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