Showing posts with label Networking. Show all posts
Showing posts with label Networking. 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 ... !!

Monday, September 26, 2011

Getting the IP Address and Hostname of the Local Machine



This code will list all interfaces and attached inet addresses on local machine, And fetch you teh actual ip address of the host.     

       
        final String hostname = InetAddress.getLocalHost().getHostName();
        String ip = InetAddress.getLocalHost().getHostAddress();
        final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface iface : Collections.list(ifaces))
        {
            /*final Enumeration<NetworkInterface> virtualIfaces = iface.getSubInterfaces();
            for (NetworkInterface viface : Collections.list(virtualIfaces))
            {
                System.out.println(iface.getDisplayName() + " VIRT " + viface.getDisplayName());
                final Enumeration<InetAddress> vaddrs = viface.getInetAddresses();
                for (InetAddress vaddr : Collections.list(vaddrs))
                {
                    System.out.println("\t" + vaddr.toString());
                }
            }*/
            final Enumeration<InetAddress> raddrs = iface.getInetAddresses();
            for (InetAddress addr : Collections.list(raddrs))
            {
                if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress())
                {  
                    ip = addr.getHostAddress();
                }
            }
        }