IPv4 可以有更多的表示形式:作为字符串 (a.b.c.d) 或数字(作为 32 位的无符号整数)。 (也许其他,但我会忽略它们。)
Java (8) 中是否有任何内置支持,简单易用,无需网络访问,可以在这些格式之间进行转换?
我需要这样的东西:
long ip = toNumerical("1.2.3.4"); // returns 0x0000000001020304L
String ipv4 = toIPv4(0x0000000001020304L); // returns "1.2.3.4"
如果 Java 中没有内置此类功能,请随时提出其他解决方案。
谢谢
最佳答案
可以使用 InetAddress
完成,如下所示。
//Converts a String that represents an IP to an int.
InetAddress i = InetAddress.getByName(IPString);
int intRepresentation = ByteBuffer.wrap(i.getAddress()).getInt();
//This converts an int representation of ip back to String
i = InetAddress.getByName(String.valueOf(intRepresentation));
String ip = i.getHostAddress();
关于java - 在java中将IP在IPv4和数字格式之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36836155/