I want to solve my problem using and I use java programming language.
views:
37answers:
2
+1
Q:
How to find which of the first 1024 ports seem to be hosting TCP based servers on a specified host?
+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
2010-10-30 06:50:07
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
2010-10-30 06:56:33
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
2010-10-31 02:11:04
Corrected. Thx.
Peter Knego
2010-10-31 06:40:25