Bellow method is validating if string is correct IPv4 address it returns true if it is valid. Any improvements in regex and elegance would be very appreciated:
public static boolean validIP(String ip) {
if (ip == null || ip.isEmpty()) return false;
ip = ip.trim();
if ((ip.length() < 6) & (ip.length() > 15)) return false;
try {
Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
} catch (PatternSyntaxException ex) {
return false;
}
}
Here is an easier-to-read, slightly less efficient, way you could go about it.
If you don't mind using dns resolution on invalid ip-addresses like
www.example.com
, you can use the InetAddress methods to check:The method checks if it is an instance of Inet4Address and if the parameter was the ip-address and not the hostname. If you expect a lot of hostnames as parameters, beware that this implementation uses DNS to try to resolve it. This might be a performance concern.
Otherwise you can have a peak into
boolean sun.net.util.IPAddressUtil.isIPv4LiteralAddress(String src)
how the String is parsed there for IPv4-check.The IPAddress Java library will do it. The javadoc is available at the link. Disclaimer: I am the project manager.
This library supports IPv4 and IPv6 transparently, so validating either works the same below, and it also supports CIDR prefix-length IPC4 addresses as well. It supports the more unusual formats like inet_aton (for example 10.8 was mentioned in another answer here)
Verify if an address is valid:
If you use the code in the question, you'll want to change the line:
to
same answer as coobird. Just add localhost to the statement. Most of the environments takes 'localhost' as a valid host name. It is not a ipv4 format but it should be included to consider validity.
In think this solution is quite elegant, although it takes a minute to understand it.
The basic idea is to take a sub-string and than validate it.
Please note that I switch x and y, since the start of a sub-string will always be the end of the last one plus 1.
This solution is about 20x faster than a regex variant and 2x faster than splitting.
If you know that you'll have a lot wrong IPs consider adding the following code below the first if. This will make the code 1.5x slower but in case of an error improve it by 700x