Get the IP Address of Your Computer using Java

This Java tutorial shows how to get the IP address of your local computer using Java. To start, you will need to get an instance of the InetAddress for the local computer. Next, you can get the string representation of the IP address from this instance.

//Get an instance of InetAddress for the local computer
InetAddress inetAddress = InetAddress.getLocalHost();

//Get a string representation of the ip address
String ipAddress = inetAddress.getHostAddress();

//Print the ip address
System.out.println(ipAddress);


8 comments:

prakash said...

In which package InetAddress class is present..?

Gizmo said...

InetAddress is in the java.net package.

faizal said...

thx for the code...

Anonymous said...

thanks

Rushil Paul said...

when i run the above code, i get the output:

2001:0:cf2e:3096:1c9e:d8df:c4a4:4326

what is this?

Anonymous said...

That is an IP address (IPv6).

rushil paul said...

no i need the IP address in da format: aaa.bbb.ccc.ddd
like 192.168.1.1

how to get that?

Anonymous said...

The original string 2001:0:cf2e:3096:1c9e:d8df:c4a4:4326 is an IPv6 IP address. This is a valid IP address. You are wanting to get the address in IPv4 format. Check out this article from Sun on networking: http://java.sun.com/j2se/1.4.2/docs/guide/net/ipv6_guide/index.html

Post a Comment