我有一个包含网络字节顺序IP地址的
int
,我想将其转换为InetAddress
对象。我看到有一个接受byte[]
参数的InetAddress
构造函数,是否需要先将int
转换为byte[]
,还是有其他方法可以实现呢?int
,我想将其转换为InetAddress
对象。我看到有一个接受byte[]
参数的InetAddress
构造函数,是否需要先将int
转换为byte[]
,还是有其他方法可以实现呢?测试并且工作正常:
int ip = ... ;
String ipStr =
String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
String.format("%d.%d.%d.%d", (ip >> 24 & 0xff), (ip >> 16 & 0xff), (ip >> 8 & 0xff), (ip & 0xff));
- Mr. Kevin Thomas这应该可以工作:
int ipAddress = ....
byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray();
InetAddress address = InetAddress.getByAddress(bytes);
你可能需要交换字节数组的顺序,我无法确定数组是否以正确的顺序生成。
bytes
数组将少于4个元素。 - user85421static public byte[] toIPByteArray(int addr){
return new byte[]{(byte)addr,(byte)(addr>>>8),(byte)(addr>>>16),(byte)(addr>>>24)};
}
static public InetAddress toInetAddress(int addr){
try {
return InetAddress.getByAddress(toIPByteArray(addr));
} catch (UnknownHostException e) {
//should never happen
return null;
}
}
InetAddresses.fromInteger
正好满足你的需求。Api文档在这里。public static byte[] int32toBytes(int hex) {
byte[] b = new byte[4];
b[0] = (byte) ((hex & 0xFF000000) >> 24);
b[1] = (byte) ((hex & 0x00FF0000) >> 16);
b[2] = (byte) ((hex & 0x0000FF00) >> 8);
b[3] = (byte) (hex & 0x000000FF);
return b;
}
我的声望不够,无法在skaffman的回答下发表评论,所以我会将这个作为一个单独的回答。
skaffman提出的解决方案是正确的,但有一个例外。BigInteger.toByteArray()返回一个字节数组,其中可能包含一个前导符号位。
byte[] bytes = bigInteger.toByteArray();
byte[] inetAddressBytes;
// Should be 4 (IPv4) or 16 (IPv6) bytes long
if (bytes.length == 5 || bytes.length == 17) {
// Remove byte with most significant bit.
inetAddressBytes = ArrayUtils.remove(bytes, 0);
} else {
inetAddressBytes = bytes;
}
InetAddress address = InetAddress.getByAddress(inetAddressBytes);
PS 上面的代码使用了 Apache Commons Lang 中的 ArrayUtils。
由于注释无法格式化,让我发布由@Mr.KevinThomas提供的代码:
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
sReturn = String.format(Locale.US, "%d.%d.%d.%d", (ipAddress >> 24 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 8 & 0xff), (ipAddress & 0xff));
它已在Android上进行了测试。
这可能有效,请尝试
public static String intToIp(int i) {
return ((i >> 24 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
( i & 0xFF);
}
public InetAddress intToInetAddress(Integer value) throws UnknownHostException
{
ByteBuffer buffer = ByteBuffer.allocate(32);
buffer.putInt(value);
buffer.position(0);
byte[] bytes = new byte[4];
buffer.get(bytes);
return InetAddress.getByAddress(bytes);
}