Java:将int转换为InetAddress

时间:2009-12-24 09:59:18

标签: java inetaddress

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

10 个答案:

答案 0 :(得分:25)

经过测试和工作:

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

答案 1 :(得分:12)

这应该有效:

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

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

答案 2 :(得分:4)

我认为这段代码更简单:

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

答案 3 :(得分:2)

如果您正在使用Google的Guava库,InetAddresses.fromInteger可以完全按照您的意愿行事。 Api文档是here

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

答案 4 :(得分:2)

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转换为字节;

答案 5 :(得分:1)

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

答案 6 :(得分:1)

使用Google Guava:

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

InetAddress address = InetAddress.getByAddress(bytes);

答案 7 :(得分:0)

由于注释无法格式化,让我发布@ 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上经过测试。

答案 8 :(得分:-1)

这可能会尝试


public static String intToIp(int i) {
        return ((i >> 24 ) & 0xFF) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >>  8 ) & 0xFF) + "." +
               ( i        & 0xFF);
    }

答案 9 :(得分:-2)

  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);
  }
相关问题