Java - 如何检测 IP 版本

2022-09-01 18:22:18

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

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

现在我想检测它是一个还是一个.IPV4IPV6


答案 1

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

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

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


答案 2

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

}

推荐