Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to detect IP version

Tags:

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.

like image 532
tokhi Avatar asked Aug 07 '13 11:08

tokhi


People also ask

How do I know if I have IPv4 or IPv6 Java?

We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address. isValid(inetAddress) : Returns true if the specified string is a valid IPv4 or IPv6 address. isValidInet4Address(inet4Address) : Returns true if the specified string is a valid IPv4 address.

How do I find my Server IP in Java?

In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress. getHostName() to get Hostname of the current Server name.

What is the best way to validate the IP address in Java?

In Java, this can be done using Pattern. matcher(). Return true if the string matches with the given regex, else return false.

How do you check if an IP address is IPv4 or IPv6?

IPv4 addresses are separated by periods, while IPv6 addresses are separated by colons. Both IP addresses are used to identify machines connected to a network.


2 Answers

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.

like image 143
Bex Avatar answered Oct 06 '22 23:10

Bex


If you are sure you're getting either an IPv4 or IPv6, you can try the following. If you have a DNS name then this will try to perform a lookup. Anyway, try this:

try {      InetAddress address = InetAddress.getByName(myIpAddr);      if (address instanceof Inet4Address) {         // your IP is IPv4     } else if (address instanceof Inet6Address) {         // your IP is IPv6     }  } catch(UnknownHostException e) {      //  your address was a machine name like a DNS name, and couldn't be found  } 
like image 25
morgano Avatar answered Oct 06 '22 23:10

morgano