Java - Validate IPv4 and IPv6 Addresses

This tutorial shows you how to check whether a value is a valid IPv4 or IPv6 address in Java.

IP address is a label that identifies each device that communicates using the Internet Protocol. There are two popular IP versions, IPv4 and IPv6.

An IPv4 address consists of octets with x.x.x.x format, where x is a decimal whose value ranges from 0 to 255. Each period is separated with a period. There are three periods separating four octets. Since an octet is 8-bit, an IPv4 address has 32-bit. That means there are 4,294,967,296 (232) possible addresses, including around 18 million addresses used as private networks and around 270 million addresses used for multicast addressing.

IPv6 comes to handle the limitation of IPv4 by using 128-bit addressing. Therefore, it has 2128 (3.403×1038) possible addresses. The format of an IPv6 address is y:y:y:y:y:y:y:y, where y is a segment whose value ranges from 0 to FFFF. Each segment is separated by a colon. There are eight segments separated by seven colons. An IPv6 address may also has a compressed version which makes validation more challenging.

Below are the validation examples using InetAddress class and regular expressions.

Using InetAddress Class

Java has a class named InetAddress from the java.net package. It can be utilized to validate IPv6 or IPv6 addresses. First, create an instance of InetAddress using the getByName static constructor by passing the IP address to be checked. If the passed value is invalid, it will throw UnknownHostException.

If the value is valid, it will return an InetAddress instance. Java actually creates an instance of Inet4Address or Inet6Address, both are sub-types of InetAddress. Therefore, you can check whether it's a valid IPv4 or IPv6 address by checking whether the instance is an instance of Inet4Address or Inet4Address respectively. For IPv4, you also need to check whether the return value of the getHostAddress method is the same as the checked value. That's because if you pass a valid domain name to the getByName static constructor, it may also return an Inet4Address instance.

  public static boolean isIPv4(String input) {
    try {
      InetAddress inetAddress = InetAddress.getByName(input);
      return (inetAddress instanceof Inet4Address) && inetAddress.getHostAddress().equals(input);
    } catch (UnknownHostException ex) {
      return false;
    }
  }

  public static boolean isIPv6(String input) {
      try {
        InetAddress inetAddress = InetAddress.getByName(input);
        return (inetAddress instanceof Inet6Address);
      } catch (UnknownHostException ex) {
        return false;
      }
  }

Then, call the above methods to validate an input.

  if (isIPv4(input)) {
    System.out.println("Valid IPv4");
  } else if (isIPv6(input)) {
    System.out.println("Valid IPv6");
  } else{ {
    System.out.println("Invalid");
  }}

Using Regex

Another way to check that a value is an IPv4 or IPv6 address is by using regular expressions. Based on the explanation above, we can create the regular expressions below.

For IPV6, there are two patterns, one for the standard (non-compressed) values and the other for compressed values.

  private static final Pattern IPV4_PATTERN = Pattern
      .compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");

  private static final Pattern IPV6_PATTERN = Pattern
      .compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
  private static final Pattern IPV6_COMPRESSED_PATTERN = Pattern
      .compile("^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");

  public static boolean isIPv4WithRegex(String input) {
    if (input == null) {
      return false;
    }

    return IPV4_PATTERN.matcher(input).matches();
  }

  public static boolean isIPv6WithRegex(String input) {
    if (input == null) {
      return false;
    }

    Matcher matcher = IPV6_PATTERN.matcher(input);

    if (matcher.matches()) {
      return true;
    }

    return IPV6_COMPRESSED_PATTERN.matcher(input).matches();
  }

Below is the usage example.

  if (isIPv4WithRegex(input)) {
    System.out.println("Valid IPv4");
  } else if (isIPv6WithRegex(input)) {
    System.out.println("Valid IPv6");
  } else{
    System.out.println("Invalid");
  }

Summary

Checking whether a string is a valid IPv4 or IPv6 address can be done in several ways. One of the solutions is by using the InetAddress class. Another solution is by using regular expressions.

You can also read about: