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();
                }
            }
        }


No comments:

Post a Comment