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

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.
package javaipscanner;

import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaIpScanner {

    Example to scan ip
    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)){
                            + " isReachable");
            } catch (UnknownHostException ex) {
                        .log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                        .log(Level.SEVERE, null, ex);


- Android version Scan Reachable IP to discover devices in network

No comments: