简体   繁体   中英

how to get IP addresses Of LAN using JAVA

I want to get IP address of my laptop that is connected into a LAN . This address has to be got from JAVA .

For this I have got the following code to get list of all IP addresses .

try
        {
            Enumeration e = NetworkInterface.getNetworkInterfaces();
            while(e.hasMoreElements())
            {
                NetworkInterface n = (NetworkInterface) e.nextElement();
                Enumeration ee = n.getInetAddresses();
                while (ee.hasMoreElements())
                {
                    InetAddress i = (InetAddress) ee.nextElement();
                    String address; 
                    address = i.getHostAddress(); 
                    System.out.println(i.getHostAddress());
                }
            } 
        }
        catch( SocketException SE)
        {
            SE.printStackTrace();
        }

Now I have got the following list of IP addresses .

127.0.0.1
0:0:0:0:0:0:0:1
192.168.10.99
fe80:0:0:0:4c55:cf87:67a0:2%10
192.168.115.215
fe80:0:0:0:a972:d8d9:c94c:4263%11
fe80:0:0:0:707c:b434:bf95:4940%12
192.168.15.1
fe80:0:0:0:1d59:66f7:e68e:31d%15 is reachable
fe80:0:0:0:1d59:66f7:e68e:31d%15
192.168.38.1
fe80:0:0:0:553f:f180:b540:75ff%16

But how can I get my LAN IP address ? My lan ip address is 192.168.10.99 .

This conde snippet helps me a lot .

 String IP()
    {
        String IP_address = "";
        int count = 0 ;
        try{
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements())
            {
                NetworkInterface current = interfaces.nextElement();
              //  System.out.println(current);
                if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
                Enumeration<InetAddress> addresses = current.getInetAddresses();
                while (addresses.hasMoreElements()){
                    InetAddress current_addr = addresses.nextElement();
                    if (current_addr.isLoopbackAddress()) continue;
                    if (current_addr instanceof Inet4Address &&  count == 0)
                    {
                        IP_address = current_addr.getHostAddress() ; 
                        System.out.println(current_addr.getHostAddress());
                         count++;
                        break;
                    }
                }
            }
        }
        catch(SocketException SE)
        {
            SE.printStackTrace();
        } 
        return  IP_address;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM