tokhi tokhi - 2 months ago 31
Java Question

Java - How to detect IP version

I'm getting

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
or an

Bex Bex

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.