java - 在java中将IP在IPv4和数字格式之间转换

标签 java ip ipv4

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/

相关文章:

希望同时使用 Inet4Address 和 Inet6Address 的 Java 应用程序

sockets - 在 IPv6 套接字上使用 `sendto()` 发送到 IPv4 地址

java - 使用 serialVersionUID 还是禁止警告?

java.lang.NoClassDefFoundError : javax/servlet/http/HttpServletRequest 错误

java - Android java ImageButton 方法帮助

java - 如何从 ContainerRequestContext JERSEY 2.1 获取 IP?

c# - 使用特定的IP(NIC上的多个IP)进行连接

c++ - 如何将 IPv4 映射的 IPv6 地址转换为 IPv4(字符串格式)?

java - JMS 连接 - 启动方法(IBM MQ impl)

ip - TCP 和 IP 数据包之间的关系