How to validate an IPV4 address in Java

An IPInternet Protocol address is a unique identifier for devices in the network to connect with each other. IPv4Internet Protocol version 4 address contains four 8-bit binary numbers, separated by a decimal point. In this answer, we will learn how to validate an IPv4 address in Java.

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 definition
public class IPv4AddressValidator {
public static void main(String[] args){
//Instance of InetAddressValidator class
InetAddressValidator validator
= InetAddressValidator.getInstance();
//validate IPv4
System.out.println(validator.isValidInet4Address("20.20.20.20"));
System.out.println(validator.isValidInet4Address("19.255.20"));
}
}

Output

true
false

Explanation

  • Line 9: We create an instance of InetAddressValidator() class and assign it to the variable validator.

  • Line 13: We validate an IPv4 address using the method isValidInet4Address by passing the IP address as a parameter. Here it returns true as it is a valid IPv4 address.

  • Line 14: Returns false as it is not a valid IPv4 address.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved