tags:

views:

37

answers:

2

I want to solve my problem using and I use java programming language.

+1  A: 

Just try to connect to them with a Socket. If you don't get a ConnectException, something is listening st that TCP port. Then do the server a favor and close the socket immediately.

What's the purpose exactly?

EJP
A: 

This is a simple code to connect to a socket with a timeout

// Create a socket with a timeout
try {
    InetAddress addr = InetAddress.getByName("java.sun.com");
    int port = 80;
    SocketAddress sockaddr = new InetSocketAddress(addr, port);

    // Create an unbound socket
    Socket sock = new Socket();

    // This method will block no more than timeoutMs.
    // If the timeout occurs, SocketTimeoutException is thrown.
    int timeoutMs = 2000;   // 2 seconds
    sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
    // Could not reach host - network error.
} catch (IOException e) {
    // Network error
}

You can just run this code in a loop to check a series of ports.

NOTE: real portscanners are much more sophisticated: http://art-exploitation.org.ua/7261final/lib0021.html

Peter Knego
The comments in your catch blocks are incorrect. SocketTimeoutException indicates a problem communicating with the host. If nothing is listening at the port you will get an immediate ConnectException, not a SocketTimeoutException.
EJP
Corrected. Thx.
Peter Knego