Friday, October 12, 2012

Getting Local IP of a system in java


The Best way to get the local IP of a system in Java?????

/**
* Gets the local IP.
*
* @return the local ip
* @throws UnknownHostException
*             the unknown host exception
* @throws SocketException
*             the socket exception
*/
public static String getLocalIP() throws UnknownHostException, SocketException
{
String ip = InetAddress.getLocalHost().getHostAddress();
final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface iface : Collections.list(ifaces))
{
final Enumeration<InetAddress> raddrs = iface.getInetAddresses();
for (InetAddress addr : Collections.list(raddrs))
{
if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress())
{
ip = addr.getHostAddress();
}
}
}
return ip;
}


Do you think is there any other way!??? It should work in all the scenarios ... !!

2 comments:

  1. Good info, But String ip = InetAddress.getLocalHost().getHostAddress(); itself is enough right??

    ReplyDelete
  2. You are right, but some times it returns you 127.0.0.1 instead of actual IP Address.!!

    ReplyDelete