Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to get own ip Address:

 
Abdul Basit
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try using

InetAddress.getAllByName("localhost");
 
Abdul Basit
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neeraj this also giving me "localhost/127.0.0.1" .
 
Abdul Basit
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yea..thanks for posting the reply Abdul!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic