1

I have a problem converting hex to IP address. For example, I have two string "b019e85" an "ac12accf" which represent IP of "11.1.158.133" and "172.18.172.207". Is there a convenient way of converting such hex string to ip address? I have read a number of answers, such as onvert-hexadecimal-string-to-ip-address and java-convert-int-to-inetaddress. But both of them do not work. Either it throws exception of "java.net.UnknownHostException: addr is of illegal length" or "java.lang.IllegalArgumentException: hexBinary needs to be even-length: b019e85 " Sample code as follows:

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I write a small utility method to convert hex to ip(only ipv4). It does not do the validity check.

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;
}
Ryder
  • 35
  • 6
  • the problem is in arguments: b019e85 is 7 digits. Needs to be 8. Even error says it... – Andrii Plotnikov Nov 21 '18 at 07:14
  • Make b019e85 into 0b019e85, then parse the parts of the string.. You can parse this with Integer.parseInt(hex,16),where hex is substring of the hex string, and construct the full IP address with StringBuilder afterwards. Out of my head, this is how I would do it – Willy Wonka Nov 21 '18 at 07:15
  • posted an answer based on suggestion in comment from user43648 – daljian Nov 21 '18 at 08:01

1 Answers1

0

Not pretty, but should work.

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();
  }
}
daljian
  • 102
  • 1
  • 11