[英]How to convert a Hex to IP address in java?
I have a problem converting hex to IP address. 我在将十六进制转换为IP地址时遇到问题。 For example, I have two string "b019e85" an "ac12accf" which represent IP of "11.1.158.133" and "172.18.172.207". 例如,我有两个字符串“ b019e85”和“ ac12accf”,分别代表IP“ 11.1.158.133”和“ 172.18.172.207”。 Is there a convenient way of converting such hex string to ip address? 是否有将这种十六进制字符串转换为IP地址的便捷方法? I have read a number of answers, such as onvert-hexadecimal-string-to-ip-address and java-convert-int-to-inetaddress . 我已经阅读了许多答案,例如onvert-hexadecimal-string-to-ip-address和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: 要么抛出异常“ java.net.UnknownHostException:addr的长度非法”,要么抛出“ java.lang.IllegalArgumentException:hexBinary必须为偶数长度:b019e85”示例代码如下:
InetAddress vipAddress = InetAddress.getByAddress(DatatypeConverter.parseHexBinary("b019e85"));
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I write a small utility method to convert hex to ip(only ipv4). 我写了一个小的实用程序方法将十六进制转换为ip(仅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;
}
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.