Monday, September 14, 2015

Java example - scan connected IP in the same network

Last post advise use Advanced IP Scanner to scan connected host in the same network. Here is a Java example to scan connected IP in the same network, using isReachable(int timeout) method of java.net.InetAddress.


public boolean isReachable(int timeout) throws IOException

Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

The timeout value, in milliseconds, indicates the maximum amount of time the try should take. If the operation times out before getting an answer, the host is deemed unreachable. A negative value will result in an IllegalArgumentException being thrown.


JavaIpScanner.java
package javaipscanner;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaIpScanner {

    /*
    Example to scan ip 192.168.1.100~120
    check if any ip is reachable, means connected host
    */
    static final String SUB_NET = "192.168.1.";

    public static void main(String[] args) {
        scanHost(SUB_NET, 100, 120);
    }

    private static void scanHost(String subnet, int lower, int upper) {
        final int timeout = 3000;

        for (int i = lower; i <= upper; i++) {
            String host = subnet + i;
            try {
                InetAddress inetAddress = InetAddress.getByName(host);
                
                if (inetAddress.isReachable(timeout)){
                    System.out.println(inetAddress.getHostName() 
                            + " isReachable");
                    System.out.println(inetAddress.toString());
                    System.out.println("--------------------");
                }
                
            } catch (UnknownHostException ex) {
                Logger.getLogger(JavaIpScanner.class.getName())
                        .log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(JavaIpScanner.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    }

}



Related:
- Android version Scan Reachable IP to discover devices in network

No comments: