java byte转ip,在java中转换IPv4和数字格式之间的IP

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.)

Is there any built in support in Java (8), simple and easy to use, without network access, to convert between these formats?

I need something like this:

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

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

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

Thank you

解决方案

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值