# Test if given ip is a public one?

I'd like to check if the user submitted adress ip is a valid public IPv4 (non loopback, non local, non reserved).

For that purpose, I came up with that method, but I was wondering if this was enough or if I was missing some tests.

private boolean isValidPublicIp(String ip) {
try
{
return true;
}
}
catch (UnknownHostException exception) {}

return false;
}

• I will assume your user only inputs valid ipv4 addresses, and not ipv6, which makes this use-case slightly outdated ... – Vogel612 Oct 8 '14 at 9:57
• Yes, I forgot to mention but I'm only targetting, for now, IPv4. – Cyril N. Oct 8 '14 at 10:02

private boolean isValidPublicIp(String ip) {
try {
} catch (UnknownHostException exception) {
return false; // assuming no logging, exception handling required
}

Reduce your try scope, and you do not need to do something like if (boolean) { return true; }. Just return boolean;. :)
edit: Your usage of ip.getBytes() for getByAddress() is actually wrong. The most straight-forward way is just to do getByName(ip), as shown here and here.