Validating IPv4 string in Java
UPDATE: Commons-HttpClient and its successor HttpComponents-HttpClient have adopted this functionality. You can utilize this version of it like so: InetAddressUtils.isIPv4Address(Str)
.
The development version of Apache Commons Validator has a InetAddressValidator
class which has a isValidInet4Address(String)
method to perform a check to see that an given String
is a valid IPv4 address.
The source code can be viewed from the repository, so that might provide some ideas for improvements, if you feel there are any.
A quick glance at the provided code shows that your method is compiling a Pattern
on each invocation of the method. I would move that Pattern
class out to a static
field to avoid the costly pattern compilation process on each call.
If you want to use a library with a released version suppporting both IPv4 and IPv6 support, you can use Guava
boolean isValid = InetAddresses.isInetAddress("1.2.3.4");
Here is an easier-to-read, slightly less efficient, way you could go about it.
public static boolean validIP (String ip) {
try {
if ( ip == null || ip.isEmpty() ) {
return false;
}
String[] parts = ip.split( "\\." );
if ( parts.length != 4 ) {
return false;
}
for ( String s : parts ) {
int i = Integer.parseInt( s );
if ( (i < 0) || (i > 255) ) {
return false;
}
}
if ( ip.endsWith(".") ) {
return false;
}
return true;
} catch (NumberFormatException nfe) {
return false;
}
}