Validate an IP address in Java
This post covers various methods to validate an IP address in Java.
An IP address in IPv4 is defined as a 32-bit number and usually represented in dot-decimal notation, consisting of four decimal numbers separated by dots, each ranging from 0 to 255, such as 172.68.58.63.
IPv6 is the successor to the IPv4 and is defined using 128 bits (or 16 octets) such as 2405:204:638b:9daa:f3c8:a903:3227:c712. Because of the historical prevalence of IPv4, the generic term IP address typically still refers to the addresses defined by IPv4.
In this post, we’ll validate IPv4 addresses by checking that given addresses consists of exactly four “decimal” numbers ranging between 0 and 255, separated by dots, i.e., the valid IP address format is xxx.xxx.xxx.xxx, where xxx lies between 0 and 255. Please note that octal or hexadecimal numbers are not permitted, i.e., 0xx, 0x, 0xA.
For example, 1.1.1.1, 127.0.0.1, 255.255.255.255, 172.68.8.63 are valid IPv4 addresses and the following IPv4 addresses are invalid:
1.1.1. (ending with a dot)
1.1..1 (two consecutive dots)
.1.1.1 (starting with a dot)
1.1.1.x (containing an alphabet)
172.8.9.256 (decimal number exceeds 255)
172.8.-9.255 (negative decimal number)
172.8.9.266 (decimal number exceeds 266)
172.013.1.2 (contains octal number 013)
172.a.1.2 (contains hexadecimal number a)
and many more…
1. Using Apache Commons Validator
Apache Commons Validator package contains several standard validation routines. We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address.
isValid(inetAddress): Returns true if the specified string is a validIPv4orIPv6address.isValidInet4Address(inet4Address): Returns true if the specified string is a validIPv4address.isValidInet6Address(inet6Address): Returns true if the specified string is a validIPv6address.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import org.apache.commons.validator.routines.InetAddressValidator; // Java program to validate `IPv4` and `IPv6` address class Main { // an IPv4 address private static final String INET4ADDRESS = "172.8.9.28"; // an IPv6 address private static final String INET6ADDRESS = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; public static void main(String[] args) { // Get an `InetAddressValidator` InetAddressValidator validator = InetAddressValidator.getInstance(); // Validate an IPv4 address if (validator.isValidInet4Address(INET4ADDRESS)) { System.out.print("The IP address " + INET4ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET4ADDRESS + " isn't valid"); } // Validate an IPv6 address if (validator.isValidInet6Address(INET6ADDRESS)) { System.out.print("The IP address " + INET6ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET6ADDRESS + " isn't valid"); } } } |
Output:
The IP address 172.8.9.28 is valid
The IP address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is valid
2. Using OWASP Validation Regex
We can also use OWASP Validation Regex, which is considered to be very safe. We can use the following regular expression to check for a valid IP Address.
^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
ESAPI validation routine can also be used which provides the following regular expression.
Validator.IPAddress=^(?:(?: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]?)$
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.util.regex.Matcher; import java.util.regex.Pattern; // Java program to validate an IPv4 address class Main { // an IPv4 address private static final String INET4ADDRESS = "172.8.9.28"; private static final String IPV4_REGEX = "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; private static final Pattern IPv4_PATTERN = Pattern.compile(IPV4_REGEX); public static boolean isValidInet4Address(String ip) { if (ip == null) { return false; } Matcher matcher = IPv4_PATTERN.matcher(ip); return matcher.matches(); } public static void main(String[] args) { // Validate an IPv4 address if (isValidInet4Address(INET4ADDRESS)) { System.out.print("The IP address " + INET4ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET4ADDRESS + " isn't valid"); } } } |
Output:
The IP address 172.8.9.28 is valid
Please note that the above regular expression will fail for "172.01.1.2" as both decimal and octal numbers are considered valid.
3. Using Guava Library
Guava InetAddresses class provides static utility methods pertaining to InetAddress instances. One such method is isInetAddress(), which checks if the specified string is a valid IP string literal or not.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import com.google.common.net.InetAddresses; // Java program to validate IPv4 and IPv6 address using Guava class Main { // an IPv4 address private static final String INET4ADDRESS = "172.8.9.28"; // an IPv6 address private static final String INET6ADDRESS = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; public static void main(String[] args) { // Validate an IPv4 address if (InetAddresses.isInetAddress(INET4ADDRESS)) { System.out.print("The IP address " + INET4ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET4ADDRESS + " isn't valid"); } // Validate an IPv6 address if (InetAddresses.isInetAddress(INET6ADDRESS)) { System.out.print("The IP address " + INET6ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET6ADDRESS + " isn't valid"); } } } |
Output:
The IP address 172.8.9.28 is valid
The IP address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is valid
4. Using Java 8
In Java 8, we can simplify things with the help of Stream, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.Arrays; // Program to validate IPv4 address in Java 8 and above class Main { public static boolean isValidInet4Address(String ip) { String[] groups = ip.split("\\."); if (groups.length != 4) { return false; } try { return Arrays.stream(groups) .filter(s -> s.length() > 1 && s.startsWith("0")) .map(Integer::parseInt) .filter(i -> (i >= 0 && i <= 255)) .count() == 4; } catch (NumberFormatException e) { return false; } } public static void main(String[] args) { // an IPv4 address final String INET4ADDRESS = "172.8.7.28"; // Validate an IPv4 address if (isValidInet4Address(INET4ADDRESS)) { System.out.print("The IP address " + INET4ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET4ADDRESS + " isn't valid"); } } } |
Output:
The IP address 172.8.7.28 isn’t valid
5. Simple Regex + Custom Validations
This solution is similar to the internal implementation of Apache Commons InetAddressValidator class discussed before.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import java.util.regex.Pattern; // Program to validate IPv4 address in Java class Main { private static final String IPV4_REGEX = "^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"; private static final Pattern IPv4_PATTERN = Pattern.compile(IPV4_REGEX); public static boolean isValidInet4Address(String ip) { if (ip == null) { return false; } if (!IPv4_PATTERN.matcher(ip).matches()) { return false; } String[] parts = ip.split("\\."); // verify that each of the four subgroups of IPv4 addresses is legal try { for (String segment: parts) { // x.0.x.x is accepted but x.01.x.x is not if (Integer.parseInt(segment) > 255 || (segment.length() > 1 && segment.startsWith("0"))) { return false; } } } catch (NumberFormatException e) { return false; } return true; } public static void main(String[] args) { // an IPv4 address final String INET4ADDRESS = "172.8.7.28"; // Validate an IPv4 address if (isValidInet4Address(INET4ADDRESS)) { System.out.print("The IP address " + INET4ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET4ADDRESS + " isn't valid"); } } } |
Output:
The IP address 172.8.7.28 is valid
6. Using InetAddress.getByName() method
Finally, we can also use the Inet4Address.getByName() provided by JDK, which causes DNS services to be accessed and checks the validity of the supplied IP address. This might not work for all theoretical valid IP addresses, and this method will be relatively slower than all other alternatives.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.net.Inet4Address; import java.net.UnknownHostException; // Program to validate IPv4 address in Java class Main { public static boolean isValidInet4Address(String ip) { try { return Inet4Address.getByName(ip) .getHostAddress().equals(ip); } catch (UnknownHostException ex) { return false; } } public static void main(String[] args) { // an IPv4 address final String INET4ADDRESS = "172.8.7.28"; // Validate an IPv4 address if (isValidInet4Address(INET4ADDRESS)) { System.out.print("The IP address " + INET4ADDRESS + " is valid"); } else { System.out.print("The IP address " + INET4ADDRESS + " isn't valid"); } } } |
Output:
The IP address 172.8.7.28 is valid
That’s all about validating an IP address in Java.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)