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;
}