Java: convert int to InetAddress

后端 未结 10 1182
既然无缘
既然无缘 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:34

    If you're using Google's Guava libraries, InetAddresses.fromInteger does exactly what you want. Api docs are here

    If you'd rather write your own conversion function, you can do something like what @aalmeida suggests, except be sure to put the bytes in the right order (most significant byte first).

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

    This should work:

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

    You might have to swap the order of the byte array, I can't figure out if the array will be generated in the correct order.

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

    This may work try

    
    public static String intToIp(int i) {
            return ((i >> 24 ) & 0xFF) + "." +
                   ((i >> 16 ) & 0xFF) + "." +
                   ((i >>  8 ) & 0xFF) + "." +
                   ( i        & 0xFF);
        }
    
    
    0 讨论(0)
  • 2020-12-14 07:37
    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;
    
    }
    

    you can use this function to turn int to bytes;

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