BraginiNI BraginiNI - 1 year ago 137
Java Question

Java: how to convert dec to 32bit int?

How to convert decimal presentation of an ip address to 32bit integer value in java?
I use InetAddress class and getLocalHost method to obtain an IP adress:

public class getIp {

public static void main(String[] args) {
InetAddress ipaddress;

try {
catch(UnknownHostException ex)


Than I should convert the result to 32bit integer value and than to string, how do I do that?

Answer Source

If the IP address is IPv6, it won’t work. Otherwise for the Sun/Oracle implementation and IPv4, you can play dirty: ipaddress.hashCode()works but may break in the future, therefore not recommended.

Otherwise (recommended): int ipv4 = ByteBuffer.wrap(addr.getAddress()).getInt()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download