Java – find all IP addresses in the local network
•
Java
I want to find all IP addresses of devices in the local network I am currently connected to using java code A useful utility, advanced IP scanner, can be found in my subnet of 192.168 Various IP addresses found in 178 / 24:
Based on the answer of this, I built my code as follows:
import java.io.IOException; import java.net.InetAddress; public class IPScanner { public static void checkHosts(String subnet) throws IOException { int timeout = 100; for (int i = 1; i < 255; i++) { String host = subnet + "." + i; if (InetAddress.getByName(host).isReachable(timeout)) { System.out.println(host + " is reachable"); } } } public static void main(String[] arguments) throws IOException { checkHosts("192.168.178"); } }
Unfortunately, this does not print any results, which means that no IP address can be accessed Why? There are devices in my local network, as shown in the advanced IP scanner scan
Solution
Try increasing the timeout I used about 5000 milliseconds, which was very helpful to me
public static void getNetworkIPs() { final byte[] ip; try { ip = InetAddress.getLocalHost().getAddress(); } catch (Exception e) { return; // exit method,otherwise "ip might not have been initialized" } for(int i=1;i<=254;i++) { final int j = i; // i as non-final variable cannot be referenced from inner class new Thread(new Runnable() { // new thread for parallel execution public void run() { try { ip[3] = (byte)j; InetAddress address = InetAddress.getByAddress(ip); String output = address.toString().substring(1); if (address.isReachable(5000)) { System.out.println(output + " is on the network"); } else { System.out.println("Not Reachable: "+output); } } catch (Exception e) { e.printStackTrace(); } } }).start(); // dont forget to start the thread } }
Work for me perfectly
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码