Reputation: 101
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.
Upvotes: 1
Views: 3270
Reputation: 12332
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;
}
Upvotes: 2
Reputation: 85
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/ ;)
Upvotes: 0