Going from 127.0.0.1 to 2130706433, and back again
String to int:
int pack(byte[] bytes) {
int val = 0;
for (int i = 0; i < bytes.length; i++) {
val <<= 8;
val |= bytes[i] & 0xff;
}
return val;
}
pack(InetAddress.getByName(dottedString).getAddress());
Int to string:
byte[] unpack(int bytes) {
return new byte[] {
(byte)((bytes >>> 24) & 0xff),
(byte)((bytes >>> 16) & 0xff),
(byte)((bytes >>> 8) & 0xff),
(byte)((bytes ) & 0xff)
};
}
InetAddress.getByAddress(unpack(packedBytes)).getHostAddress()
You can also use the Google Guava InetAddress Class
String ip = "192.168.0.1";
InetAddress addr = InetAddresses.forString(ip);
// Convert to int
int address = InetAddresses.coerceToInteger(addr);
// Back to str
String addressStr = InetAddresses.fromInteger(address));