As a tangent to a larger project, I'm trying to implement some code to scan for open ports so that I may eventually run a packet test. At the moment I am just trying to connect to google.com and I know that port 80 accepts a connection, so I've formatted my code to scan a range of ports including this one. However, whilst I can connect directly to port 80, the scanner code seems to pass it by. I was wondering if anyone had any thoughts?
public class PortScanner {
public static void main(String[] args) throws IOException {
Socket socket = new Socket();
String host = "www.google.com";
System.out.println("Attempting to connect to " + host + " at port 80...");
try {
socket.connect(new InetSocketAddress(host, 80), 5000);
System.out.println("Connection Successful.");
}
catch (Exception e) {
//Just bypass the exceptions for now
}
System.out.println("Scanning for open ports on " + host);
for (int i = 75; i < 85; i++) {
System.out.println("Attempting to connect to " + host + " on port " + i);
try {
socket.connect(new InetSocketAddress(host, i), 5000);
System.out.println("Open port found at " + i);
}
catch (ConnectException e) {
System.err.println("Connect Exception Thrown on Port " + i);
continue;
}
catch (SocketException e) {
System.err.println("Socket Exception Thrown on Port " + i);
continue;
}
catch (UnknownHostException e) {
System.err.println("Unknown host at " + host);
System.exit(1);
}
}
System.out.println("Closing connection to " + host);
socket.close();
System.out.println("Connection closed");
}
}
In fact, the loop reports that there is a SocketException thrown at port 80:
Attempting to connect to www.google.com at port 80...
Connection Successful.
Scanning for open ports on www.google.com
Socket Exception Thrown on Port 75
Socket Exception Thrown on Port 76
Socket Exception Thrown on Port 77
Socket Exception Thrown on Port 78
Socket Exception Thrown on Port 79
Socket Exception Thrown on Port 80
Socket Exception Thrown on Port 81
Socket Exception Thrown on Port 82
Socket Exception Thrown on Port 83
Attempting to connect to www.google.com on port 75
Socket Exception Thrown on Port 84
Attempting to connect to www.google.com on port 76
Attempting to connect to www.google.com on port 77
Attempting to connect to www.google.com on port 78
Attempting to connect to www.google.com on port 79
Attempting to connect to www.google.com on port 80
Attempting to connect to www.google.com on port 81
Attempting to connect to www.google.com on port 82
Attempting to connect to www.google.com on port 83
Attempting to connect to www.google.com on port 84
Closing connection to www.google.com
Connection closed
The fact that the console logs are coming out in the order that they are made me wonder if the connection attempts were perhaps coming in too quickly and thus causing the program to miss the ports that are available, but I'm not really sure what to do about that.
Any thoughts appreciated!