我Client
通过以下方法获取 IP 地址:
public static String getClientIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
...
return ip
}
现在我想检测它是一个IPV4
还是一个IPV6
。
我Client
通过以下方法获取 IP 地址:
public static String getClientIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
...
return ip
}
现在我想检测它是一个IPV4
还是一个IPV6
。
您可以创建一个 InetAddress 并检查它是否成为 ipv4 或 ipv6 实例
InetAddress address = InetAddress.getByName(ip);
if (address instanceof Inet6Address) {
// It's ipv6
} else if (address instanceof Inet4Address) {
// It's ipv4
}
不过,这似乎有点尴尬,我希望有更好的解决方案。
如果您确定您获得的是 IPv4 或 IPv6,您可以尝试以下操作。如果您有 DNS 名称,那么这将尝试执行查找。无论如何,试试这个:
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
}
您可以使用来自 google guava 的 InetAddresses。例如像这样:
int addressLength = InetAddresses.forString(ip).getAddress().length;
switch (addressLength) {
case 4:
System.out.println("IPv4");
break;
case 16:
System.out.println("IPv6");
break;
default:
throw new IllegalArgumentException("Incorrect ip address length " + addressLength);
}