Java – How To check if an IP address is IPv4 or IPv6
This article shows you how to check if an IP address is IPv4 or IPv6 in Java.
IPAddress.java
package com.bytenota;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPAddress {
public static boolean isIPv4(String ipAddress) {
boolean isIPv4 = false;
if (ipAddress != null) {
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
isIPv4 = (inetAddress instanceof Inet4Address) && inetAddress.getHostAddress().equals(ipAddress);
} catch (UnknownHostException ex) {
}
}
return isIPv4;
}
public static boolean isIPv6(String ipAddress) {
boolean isIPv6 = false;
if (ipAddress != null) {
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
isIPv6 = (inetAddress instanceof Inet6Address);
} catch (UnknownHostException ex) {
}
}
return isIPv6;
}
}
In the above IPAddress
class, we have implemented the following methods:
isIPv4
method: that checks if an IP address is IPv4 or notisIPv6
method: that checks if an IP address is IPv6 or not
Use the methods:
Program.java
package com.bytenota;
public class Program {
public static void main(String[] args) {
String ipAddress = "2001:db8:a0b:12f0::1";
//String ipAddress = "42.197.20.45";
if (IPAddress.isIPv4(ipAddress)) {
System.out.println("This is IPv4");
} else if (IPAddress.isIPv6(ipAddress)) {
System.out.println("This is IPv6");
} else {
System.out.println("Invalid IP address");
}
}
}
A big drawback of using this approach is the DNS check used by the InetAddress constructor. The implementation is clean but it has a major and possibly hidden side effect.