23

Client通过以下方法获取 IP 地址:

public static String getClientIpAddr(HttpServletRequest request) {  
    String ip = request.getHeader("X-Forwarded-For");  
    ...
    return ip
} 

现在我想检测它是一个IPV4还是一个IPV6

4

3 回答 3

41

您可以创建一个 InetAddress 并检查它是否成为 ipv4 或 ipv6 实例

InetAddress address = InetAddress.getByName(ip);
if (address instanceof Inet6Address) {
    // It's ipv6
} else if (address instanceof Inet4Address) {
    // It's ipv4
}

不过,这似乎有点尴尬,我希望有更好的解决方案。

于 2013-08-07T12:06:15.443 回答
10

如果您确定您获得的是 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

}
于 2013-08-07T12:18:05.320 回答
4

您可以使用来自 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);
}
于 2018-12-01T19:23:32.277 回答