Search code examples
javainetaddress

Java: convert int to InetAddress


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 InetAddress constructor that takes a byte[], is it necessary to convert the int to a byte[] first, or is there another way?


Solution

  • 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.