How to validate an IPV4 address in Java
An
We will use the Apache Commons Validator dependency to validate an IPv4 address using the method isValidInet4Address.
To use this method, we need to install the dependency Apache Commons Validator.
Add the below code in your pom.xml file:
<dependency><groupId>commons-validator</groupId><artifactId>commons-validator</artifactId><version>1.7</version></dependency>
Syntax
isValidInet4Address("provide ip here"))
Example
import org.apache.commons.validator.routines.InetAddressValidator;//class definitionpublic class IPv4AddressValidator {public static void main(String[] args){//Instance of InetAddressValidator classInetAddressValidator validator= InetAddressValidator.getInstance();//validate IPv4System.out.println(validator.isValidInet4Address("20.20.20.20"));System.out.println(validator.isValidInet4Address("19.255.20"));}}
Output
truefalse
Explanation
Line 9: We create an instance of
InetAddressValidator()class and assign it to the variablevalidator.Line 13: We validate an IPv4 address using the method
isValidInet4Addressby passing the IP address as a parameter. Here it returnstrueas it is a valid IPv4 address.Line 14: Returns false as it is not a valid IPv4 address.
Free Resources