在java中转换IPv4和数字格式之间的IP [英] Convert IP between IPv4 and numerical format in java

查看:859
本文介绍了在java中转换IPv4和数字格式之间的IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IPv4可以有更多的表示形式:字符串(a.b.c.d)或数字(作为32位的无符号整数)。 (也许其他,但我会忽略它们。)

An IPv4 can have more representations: as string (a.b.c.d) or numerical (as an unsigned int of 32 bits). (Maybe other, but I will ignore them.)

Java(8)中是否有内置支持,简单易用,无需网络访问,在这些格式之间进行转换?

我需要这样的东西:

long ip = toNumerical("1.2.3.4"); // returns 0x0000000001020304L
String ipv4 = toIPv4(0x0000000001020304L); // returns "1.2.3.4"

如果Java中没有内置此类函数,请随意建议其他解决方案。

If there is no built in such functions in Java, feel free to suggest other solutions.

谢谢

推荐答案

可以使用 InetAddress 完成,如下所示。

The can be done using InetAddress as follows.

   //Converts a String that represents an IP to an int.
   InetAddress i= InetAddress.getByName(IPString);
   int intRepresentation= ByteBuffer.wrap(i.getAddress()).getInt();

   //This convert an int representation of ip back to String
   i= InetAddress.getByName(String.valueOf(intRepresentation));
   String ip= i.getHostAddress();

这篇关于在java中转换IPv4和数字格式之间的IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆