Tuesday 18 August 2015

Java program to validate IPV4, IPV6 addresses

IPV4 address
IPV4 address consists of 32 bits and represented in dot notation like 172.16.254.1. Each part in address is represented using 8 bits.

IPV6 address
IPv6 address is made of 128 bits divided into eight 16-bits blocks.
Each block is converted into 4-digit Hexadecimal numbers separated by colon symbols.
Ex: 2911:1134:3238:DFE1:0063:0000:5432:FEFB

Apache commons-validator provide methods to validate IP addresses.

Validate IP address using Apache commons-validator
InetAddressValidator class provides following methods, to validate IP address.


Method
Description
public boolean isValid(String inetAddress)
Returns true if string is valid IPV4 or IPV6 address.
public boolean isValidInet4Address(String inet4Address)
Returns true, if the argument is valid IPV4 address.
public boolean isValidInet6Address(String inet6Address)
Returns true, if the argument is valid IPV6 address.

import org.apache.commons.validator.routines.InetAddressValidator;

public class IPAddressUtil {

 public static void main(String args[]) {
  InetAddressValidator inetAddressValidator = InetAddressValidator
    .getInstance();
  String address = "192.168.1.231";

  System.out.println("Is Valid IP address : "
    + inetAddressValidator.isValid(address));
  System.out.println("Is Valid IPV4 address : "
    + inetAddressValidator.isValidInet4Address(address));
  System.out.println("Is Valid IPV6 address : "
    + inetAddressValidator.isValidInet6Address(address));
 }
}


Output
Is Valid IP address : true
Is Valid IPV4 address : true
Is Valid IPV6 address : false

Note:
Guava package also provides “com.google.common.net.InetAddresses” class to validate IPaddresses.







No comments:

Post a Comment