vendredi, 19 novembre 2010

Using java.net.InetAddress.getByName() to validate an IP Address may be too permissive

java.net.InetAddress.getByName() static function can be used for validating a given IP Address.

But doing that way you need to pay attention to certain side effects border values :

String ip = "1.2.3.4"; // valid IP Address
InetAddress address = InetAddress.getByName( ip );
Assert.assertEquals( ip, address.getHostAddress() ); // Pass. OK

String ip = "1.2.3"; // invalid IP Address
InetAddress address = InetAddress.getByName( ip );
Assert.assertEquals( ip, address.getHostAddress() ); // Pass. KO !
If you have a look a little deeper, you will see that 1.2.3 is transformed in 1.2.0.3, which after transformation become a valid IP Address.

Having that in mind, a IP Address validation function can look like :
public static boolean validateIpAddress( String anIpAddress ) {
try {
InetAddress address = InetAddress.getByName( anIpAddress );
return address.getHostAddress().equals( anIpAddress );
} catch (final UnknownHostException e) {
return false;
}
}