A while back, I told you about a book I was once working on called “Quick Coding and Automation with Java“. In the book from the article, I include all kinds of small programs that can be used right out-of-the box for doing many different things. One of those programs was a simple port scanner that could scan the entire port range on a computer all the way up to port 65535. In case you haven’t read the book or you’re simply looking for a quick reference to creating a port scanner using Java, I’m going to show you how to do that now.
To create a port scanner using Java, we’re going to use the same utilities we used in our Java HTTP client from yesterday. We will begin with the InetAddress object. This is the object that will get us a reference to the computer that we will be scanning. In the code below, I use “localhost” as my remote target, but you can swap this out with any computer name on your network. In fact, since you already know the computer name of your target, the InetAddress isn’t really necessary. But, I threw it in there anyways since I had planned on extending the application at a later point. Because you already know the computer name of your target machine, you can hard code it directly.
Since we already know that computers have a set range of ports, we can use a standard for-loop that ranges from 1 to 65535 and use the Socket to test each of the ports in that range. To use the socket, you’ll need to pass the computer name we got before and the port number we want to test. The only thing we need to do to test if the port is listening or not is to attempt to have the Socket open and close the port. If it can open and close the port, we obviously know that the port is listening. Later on I’ll show you how to determine what daemons are running on each of those ports. But for now, we will simply print the open port numbers to our console.
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class PortScanner {
public static void main(String[] args) throws Exception {
InetAddress remote = InetAddress.getByName("localhost");
String hostname = remote.getHostName();
for (int port = 1; port <= 65535; port++) {
try {
Socket s = new Socket(remote, port);
System.out.println("Something is listening for connections on port " + port + " of " + hostname);
s.close();
}
catch (IOException ex) {
// The remote host is not listening on this port
}
}
}
}
