Java: convert int to InetAddress

kdt picture kdt · Dec 24, 2009 · Viewed 35.5k times · Source

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?

Answer

hbr picture hbr · May 20, 2013

Tested and working:

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