Fastest way to scan ports with Java

Viewed 63744

I made a very simple port scanner, but it runs too slow, so I'm looking for a way to make it scan faster. Here is my code:

public boolean portIsOpen(String ip, int port, int timeout) {
    try {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), timeout);
        socket.close();
        return true;
    } catch (Exception ex) {
        return false;
    }
}

This code tests if a specific port is open on a specific ip. For timeout I used a minimum value of 200 because when I go lower it doesn't have enough time to test the port.

It works well, but takes too much to scan from 0 to 65535. Is there any other way that could maybe scan from 0 to 65535 in less than 5 minutes?

7 Answers

Nay, fastest way here is to use the dynamically created thread method

Executors.newCachedThreadPool();

This way it uses threads until all of them are taken, then when all of them are taken and there is a new task it will open up a new thread and preform the new task on it.

Here's my code snippet (Creds due to Jack and Bruno Reis)

I also added the function to search any IP address you type in for some added functionality and ease of use.

    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;

    class PortScanner {

    public static void main(final String... args) throws InterruptedException, ExecutionException 
    {
        final ExecutorService es = Executors.newCachedThreadPool();
        System.out.print("Please input the ip address you would like to scan for open ports: ");
        Scanner inputScanner = new Scanner(System.in);
        final String ip = inputScanner.nextLine();
        final int timeout = 200;
        final List<Future<ScanResult>> futures = new ArrayList<>();
        for (int port = 1; port <= 65535; port++) {
            // for (int port = 1; port <= 80; port++) {
            futures.add(portIsOpen(es, ip, port, timeout));
        }
        es.awaitTermination(200L, TimeUnit.MILLISECONDS);
        int openPorts = 0;
        for (final Future<ScanResult> f : futures) {
            if (f.get().isOpen()) {
                openPorts++;
                System.out.println(f.get().getPort());
            }
        }
        System.out.println("There are " + openPorts + " open ports on host " + ip + " (probed with a timeout of "
        + timeout + "ms)");
 es.shutdown();
    }



    public static Future<ScanResult> portIsOpen(final ExecutorService es, final String ip, final int port,
    final int timeout) 
    {
        return es.submit(new Callable<ScanResult>() {
            @Override
            public ScanResult call() {
                try {
                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress(ip, port), timeout);
                    socket.close();
                    return new ScanResult(port, true);
                } catch (Exception ex) {
                    return new ScanResult(port, false);
                }
            }
        });
    }

    public static class ScanResult {
private int port;

private boolean isOpen;

public ScanResult(int port, boolean isOpen) {
    super();
    this.port = port;
    this.isOpen = isOpen;
}

public int getPort() {
    return port;
}

public void setPort(int port) {
    this.port = port;
}

public boolean isOpen() {
    return isOpen;
}

public void setOpen(boolean isOpen) {
    this.isOpen = isOpen;
}

    }
    }

I may be late to this but you can do a bulk port scan by doing the following using NIO2 single-threaded. By following NIO2 code with a single thread, I am able to scan all the hosts for a given port. Please try a reasonable timeout and make sure you have large File Discriptor for process

public static List<HostTarget> getRechabilityStatus(String...hosts,final int port, final int bulkDevicesPingTimeoutinMS) throws Exception {

    List<AsynchronousSocketChannel> channels = new ArrayList<>(hosts.length);
    try {
        List<CompletableFuture<HostTarget>> all = new ArrayList<>(hosts.length);

        List<HostTarget> allHosts = new ArrayList(hosts.length);
        for (String host : hosts) {
            InetSocketAddress address = new InetSocketAddress(host, port);
            HostTarget target = new HostTarget();
            target.setIpAddress(host);
            allHosts.add(target);
            AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
            channels.add(client);
            final CompletableFuture<HostTarget> targetFuture = new CompletableFuture<>();
            all.add(targetFuture);
            client.connect(address, target, new CompletionHandler<Void, HostTarget>() {
                @Override
                public void completed(Void result, HostTarget attachment) {
                    attachment.setIsReachable(true);
                    targetFuture.complete(attachment);
                }

                @Override
                public void failed(Throwable exc, HostTarget attachment) {
                    attachment.setIsReachable(false);
                    attachment.errrorMessage = exc.getMessage();
                    targetFuture.complete(attachment);
                }
            });
        }

        try {
            if(bulkDevicesPingTimeoutinMS > 0) {
                CompletableFuture.allOf(all.toArray(new CompletableFuture[]{})).get(bulkDevicesPingTimeoutinMS, TimeUnit.MILLISECONDS);
            }else{
                // wait for all future to be complete 1000 scan is taking 7 seconds.
                CompletableFuture.allOf(all.toArray(new CompletableFuture[]{})).join();
            }
        } catch (Exception timeoutException) {
            // ignore
        }
        return allHosts;
    }finally {
        for(AsynchronousSocketChannel channel : channels){
            try{
                channel.close();
            }catch (Exception e){
                if(LOGGER.isDebugEnabled()) {
                    LOGGER.error("Erorr while closing socket",e);
                }
            }

        }
    }
static class HostTarget {

String ipAddress;
Boolean isReachable;
 public String getIpAddress() {
    return ipAddress;
}
public Boolean getIsReachable() {
    return isReachable;
}

public void setIpAddress(String ipAddress) {
    this.ipAddress = ipAddress;
}
public void setIsReachable(Boolean isReachable) {
    this.isReachable = isReachable;
}

}
Related