如何在Java中将十六进制转换为IP地址?

时间:2018-11-21 07:07:39

标签: java ip hex

我在将十六进制转换为IP地址时遇到问题。 例如,我有两个字符串“ b019e85”和“ ac12accf”,分别代表IP“ 11.1.158.133”和“ 172.18.172.207”。是否有将这种十六进制字符串转换为IP地址的便捷方法? 我已经阅读了许多答案,例如onvert-hexadecimal-string-to-ip-addressjava-convert-int-to-inetaddress。 但是它们都不起作用。它抛出“ java.net.UnknownHostException:addr的长度非法”或“ java.lang.IllegalArgumentException:hexBinary需要为偶数长度:b019e85”的异常 ” 示例代码如下:

            InetAddress vipAddress = InetAddress.getByAddress(DatatypeConverter.parseHexBinary("b019e85"));

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 〜

我写了一个小的实用程序方法来将十六进制转换为ip(仅ipv4)。它不进行有效性检查。

private String getIpByHex(String hex) {
    Long ipLong = Long.parseLong(hex, 16);
    String ipString = String.format("%d.%d.%d.%d", ipLong >> 24, 
        ipLong >> 16 & 0x00000000000000FF, 
        ipLong >> 8 & 0x00000000000000FF, 
        ipLong & 0x00000000000000FF);

    return ipString;
}

1 个答案:

答案 0 :(得分:-1)

不漂亮,但应该可以。

public class IpTest {
  public static void main(String[] args) throws Exception {
    String hexAddrString1 = "b019e85";
    String hexAddrString2 = "ac12accf";
    System.out.println("ip:" + getIpFromHex(hexAddrString1));
    System.out.println("ip:" + getIpFromHex(hexAddrString2));
    //To get InetAddress
    InetAddress vipAddress1 = InetAddress.getByName(getIpFromHex(hexAddrString1));
    InetAddress vipAddress2 = InetAddress.getByName(getIpFromHex(hexAddrString2));
  }

  public static String getIpFromHex(String hexAddrString) {
    if (hexAddrString.length() % 2 != 0) {
      hexAddrString = "0" + hexAddrString;
    }
    if (hexAddrString.length() != 8) {
      //error..
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hexAddrString.length(); i = i + 2) {
      final String part = hexAddrString.substring(i, i + 2);
      final int ipPart = Integer.parseInt(part, 16);
      if (ipPart < 0 || ipPart > 254) {
        //Error...
      }
      sb.append(ipPart);
      if (i + 2 < hexAddrString.length()) {
        sb.append(".");
      }
    }
    return sb.toString();
  }
}