Java: convert int to InetAddress

后端 未结 10 1181
既然无缘
既然无缘 2020-12-14 06:34

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 <

相关标签:
10条回答
  • 2020-12-14 07:12

    Not enough reputation to comment on skaffman's answer so I'll add this as a separate answer.

    The solution skaffman proposes is correct with one exception. BigInteger.toByteArray() returns a byte array which could have a leading sign bit.

    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 above code uses ArrayUtils from Apache Commons Lang.

    0 讨论(0)
  • 2020-12-14 07:19
      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);
      }
    
    0 讨论(0)
  • 2020-12-14 07:21

    Since comments cannot be formatted, let me post the code derived from the comment by @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));
    

    It has been tested on Android.

    0 讨论(0)
  • 2020-12-14 07:24

    Tested and working:

    int ip  = ... ;
    String ipStr = 
      String.format("%d.%d.%d.%d",
             (ip & 0xff),   
             (ip >> 8 & 0xff),             
             (ip >> 16 & 0xff),    
             (ip >> 24 & 0xff));
    
    0 讨论(0)
  • 2020-12-14 07:24

    I think that this code is simpler:

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-14 07:28

    Using Google Guava:

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

    InetAddress address = InetAddress.getByAddress(bytes);

    0 讨论(0)
提交回复
热议问题