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
.
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.
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.
In Java, this can be done using Pattern. matcher(). Return true if the string matches with the given regex, else return false.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With