wood burning stoves 2.0*
The moose likes Sockets and Internet Protocols and the fly likes How to get own ip Address: Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "How to get own ip Address:" Watch "How to get own ip Address:" New topic
Author

How to get own ip Address:

Abdul Basit
Greenhorn

Joined: Jan 25, 2002
Posts: 27
I am finding ip address of my own PC from where i am executing my code. I am on LAN and has local ip address 192.168.1.2. What i am doing you can see in a below code.

public class Test {
public static void main(String[] args) throws Exception{
try
{

InetAddress localaddr = InetAddress.getLocalHost();
System.out.println( "main Local IP Address : " + localaddr.getHostAddress() );
System.out.println( "main Local hostname : " + localaddr.getHostName() );

}
catch ( UnknownHostException e )
{
System.err.println( "Can't detect localhost : " + e);
}
}
}

This code outputs loop-back address 127.0.0.1 and host name of my PC, what a huge work this code does, but i am interested in eth0 interface address which is �192.168.1.2�.
any suggestion how can i get my PC local LAN ip via code.
Regards
MABASIT
Neeraj Dheer
Ranch Hand

Joined: Mar 30, 2005
Posts: 225
try using

InetAddress.getAllByName("localhost");
Abdul Basit
Greenhorn

Joined: Jan 25, 2002
Posts: 27
Neeraj this also giving me "localhost/127.0.0.1" .
Abdul Basit
Greenhorn

Joined: Jan 25, 2002
Posts: 27
This code give you all interfaces ip addresses.

Enumeration enum = NetworkInterface.getNetworkInterfaces();

while(enum.hasMoreElements())
{

NetworkInterface ia= (NetworkInterface)enum.nextElement();
Enumeration enuminet = ia.getInetAddresses();

while(enuminet.hasMoreElements())
{

InetAddress inet = (InetAddress) enuminet.nextElement();
System.out.println(inet.getHostAddress());
}
}
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Hey, Abdul, thanks for posting your solution! It's nice for others (like me) who stumble upon the thread and are curious as to the solution, especially when we've got the same question. That's part of the JavaRanch spirit.
Neeraj Dheer
Ranch Hand

Joined: Mar 30, 2005
Posts: 225
yea..thanks for posting the reply Abdul!!!
 
Consider Paul's rocket mass heater.
 
subject: How to get own ip Address: