Java:将int转换为InetAddress

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

这应该工作:

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

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

经过测试和工作:

 int ip = ... ; String ipStr = String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff)); 

我认为这段代码更简单:

 static 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; } } 
 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; } 

您可以使用此函数将int转换为字节;

如果您使用的是Google的Guava库, InetAddresses.fromInteger可以完全满足您的需求。 Api文档在这里

如果您更愿意编写自己的转换函数,您可以执行类似@aalmeida建议的操作,除非确保以正确的顺序放置字节(最重要的字节优先)。

没有足够的声誉评论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。

使用Google Guava:

byte [] bytes = Ints.toByteArray(ipAddress);

InetAddress address = InetAddress.getByAddress(bytes);

这可能会尝试

 public static String intToIp(int i) { return ((i >> 24 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) + "." + ((i >> 8 ) & 0xFF) + "." + ( i & 0xFF); }
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); }