Java Reference
In-Depth Information
Example 8-5. Find out which of the first 1024 ports seem to be hosting TCP servers on a
specified host
import java.net.* ;
import java.io.* ;
public class LowPortScanner {
public static void main ( String [] args ) {
String host = args . length > 0 ? args [ 0 ] : "localhost" ;
for ( int i = 1 ; i < 1024 ; i ++) {
try {
Socket s = new Socket ( host , i );
System . out . println ( "There is a server on port " + i + " of "
+ host );
s . close ();
} catch ( UnknownHostException ex ) {
System . err . println ( ex );
break ;
} catch ( IOException ex ) {
// must not be a server on this port
}
}
}
}
Here's the output this program produces on my local host (your results will vary, de‐
pending on which ports are occupied):
$ java LowPortScanner
There is a server on port 21 of localhost
There is a server on port 22 of localhost
There is a server on port 23 of localhost
There is a server on port 25 of localhost
There is a server on port 37 of localhost
There is a server on port 111 of localhost
There is a server on port 139 of localhost
There is a server on port 210 of localhost
There is a server on port 515 of localhost
There is a server on port 873 of localhost
If you're curious about what servers are running on these ports, try experimenting with
Telnet. On a Unix system, you may be able to find out which services reside on which
ports by looking in the file /etc/services . If LowPortScanner finds any ports that are
running servers but are not listed in /etc/services , then that's interesting.
Although this program looks simple, it's not without its uses. The first step to securing
a system is understanding it. This program helps you understand what your system is
doing so you can find (and close) possible entrance points for attackers. You may also
Search WWH ::




Custom Search