tokhi tokhi - 7 days ago 7
Java Question

Java - How to detect IP version

I'm getting

Client
IP address via below method :

public static String getClientIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
...
return ip
}


Now I want to detect if it is an
IPV4
or an
IPV6
.

Bex Bex
Answer

You could create an InetAddress and check if it became an ipv4 or ipv6 instance

InetAddress address = InetAddress.getByName(ip);
if (address instanceof Inet6Address) {
    // It's ipv6
} else if (address instanceof Inet4Address) {
    // It's ipv4
}

It seems a bit awkward, though, and I hope there is a better solution.