tokhi tokhi - 1 year ago 105
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
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download