Showing posts with label ip. Show all posts
Showing posts with label ip. Show all posts

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 ... !!