Search code examples
javanetworkingipsubnet

Get all the Up ip in the local network -java


For the Java project i need to scan the list of ip connected to the same local network via wlan or eth0 or anything. I need to get the list of ip address that are up in the local network.

I tried

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) 
{
        System.out.println(address.getNetworkPrefixLength());
}

But it gives

Exception in thread "main" java.lang.NullPointerException
at com.Server.Subnet.main(Subnet.java:17)

I think i need to follow these steps.

  1. Get the subnet address of the network that i connected
  2. Scan all the ip address in the subnet mask
  3. List the ip address that are up

Can you give me the right implementation way


Solution

  • I tried this program to find all the up ip in the subnet of the system connected.

    package com.Server;
    
    import java.io.IOException;
    import java.net.Inet4Address;
    import java.net.InetAddress;
    import java.net.InterfaceAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Enumeration;
    
    public class Subnet
    {
        public void Subnet() throws UnknownHostException, SocketException
        {
            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 ip = i.getHostAddress();
    
                    String sip = ip.substring(0, ip.indexOf('.',ip.indexOf('.',ip.indexOf('.')+1) + 1) + 1);
                    try {
                        for(int it=1;it<=255;it++)
                        {
                            String ipToTest = sip+it;
                            boolean online = InetAddress.getByName(itToTest).isReachable(100);
                            if (online) {
                                System.out.println(ipToTest+" is online");
                            }
    
                        }
                    } catch (IOException e1) {
                        System.out.println(sip);
                    }
                }
            }
        }
    }