Skip to content

Instantly share code, notes, and snippets.

@yousefamar
Created December 17, 2014 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yousefamar/07b6ce99a31e892019a2 to your computer and use it in GitHub Desktop.
Save yousefamar/07b6ce99a31e892019a2 to your computer and use it in GitHub Desktop.
A program that repeatedly lists the IP addresses of all devices on a LAN at one second intervals
import java.net.*;
import java.lang.*;
import java.util.*;
public class IPScanner implements Runnable {
// Create a list in which to store live host IP addresses
static List<String> ips = Collections.synchronizedList(new ArrayList<String>());
private String ip;
public IPScanner(String ip) {
this.ip = ip;
}
/**
* Checks if the IP address #ip is reachable with a timeout of one second.
*/
public void run() {
try {
if(InetAddress.getByName(this.ip).isReachable(1000))
IPScanner.ips.add(this.ip);
} catch(Exception e) {
// TODO: Handle properly
System.err.println(e);
}
}
public static void main(String[] args) {
Thread[] threads = new Thread[256];
while (true) {
IPScanner.ips.clear();
// Create 256 threads for every possible private IP address
// and check reachability of hosts at all IPs concurrently
for (int i = 0; i < 256; ++i) {
// Depending on your network, this could be 192.168.*.* or 10.*.*.* or whatever
threads[i] = new Thread(new IPScanner("192.168.0." + i));
threads[i].start();
}
// Wait for all threads to finish
for (Thread thread : threads)
try { thread.join(); } catch (InterruptedException e) {}
// Sort list of IPs for temporal consistency
// (just alphabetical; numerical might look better)
Collections.sort(IPScanner.ips);
// Print out results
System.out.println("IPs:");
for (String ip : IPScanner.ips)
System.out.println(ip);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment