将int转换为InetAddress

将int转换为InetAddress

本文介绍了Java:将int转换为InetAddress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 int ,其中包含网络字节顺序的IP地址,我想将其转换为 InetAddress 对象。我看到有一个 InetAddress 构造函数,它接受 byte [] ,是否需要转换 int 首先到 byte [] ,还是有另一种方式?

I have an int which contains an IP address in network byte order, which I would like to convert to an InetAddress object. I see that there is an InetAddress constructor that takes a byte[], is it necessary to convert the int to a byte[] first, or is there another way?

推荐答案

这应该有效:

int ipAddress = ....
byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray();
InetAddress address = InetAddress.getByAddress(bytes);

您可能必须交换字节数组的顺序,我无法弄清楚数组是否存在将以正确的顺序生成。

You might have to swap the order of the byte array, I can't figure out if the array will be generated in the correct order.

这篇关于Java:将int转换为InetAddress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:38