Java:将int转换为InetAddress


问题内容

我有一个int以网络字节顺序包含IP地址的地址,我想将其转换为InetAddress对象。我看到有一个InetAddress采用的构造函数byte[],是否有必要将转换intbyte[]第一个,还是有其他方法?


问题答案:

这应该工作:

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

您可能需要交换字节数组的顺序,但我无法弄清楚是否会以正确的顺序生成该数组。