Java - 如何检测IP版本

时间:2013-08-07 11:51:26

标签: java servlets network-programming

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

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

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

4 个答案:

答案 0 :(得分:25)

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

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

虽然看起来有点尴尬,但我希望有更好的解决方案。

答案 1 :(得分:8)

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

}

答案 2 :(得分:1)

您可以使用来自Google番石榴的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);
}

答案 3 :(得分:-1)

感谢Tala

这是我尝试使用this example进行微小更改的内容:

  private static Pattern VALID_IPV4_PATTERN = null;
  private static Pattern VALID_IPV6_PATTERN = null;
  private static final String ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
  private static final String ipv6Pattern = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";

  static {
    try {
      VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
      VALID_IPV6_PATTERN = Pattern.compile(ipv6Pattern, Pattern.CASE_INSENSITIVE);
    } catch (PatternSyntaxException e) {
      //logger.severe("Unable to compile pattern", e);
    }
  }

  public static String isIpAddressV4orV6(String ipAddress) {

        Matcher ipv4 = IP_Utilities.VALID_IPV4_PATTERN.matcher(ipAddress);
        if (ipv4.matches()) {
          return "IPV4";
        }
        Matcher ipv6 = IP_Utilities.VALID_IPV6_PATTERN.matcher(ipAddress);
        if (ipv6.matches()) {
              return "IPV6";
        }
        return "";
    }