作为大型项目的切线,我试图实现一些代码来扫描开放端口,以便最终运行数据包测试。目前我只是想连接到google.com,我知道端口80接受连接,所以我已经格式化了我的代码来扫描包括这个端口在内的一系列端口。然而,虽然我可以直接连接到端口80,但扫描器代码似乎通过了它。我想知道是否有人有任何想法?
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");
}
}
实际上,循环报告在端口80处抛出了SocketException:
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
控制台日志按照它们的顺序出现的事实我想知道连接尝试是否可能过快而导致程序错过了可用的端口,但是我是不知道该怎么做。
任何想法都赞赏!
答案 0 :(得分:1)
Socket
最多只能用于1个活动连接!并且由于您在端口扫描开始时进行连接(并且仅在结束时关闭它),因此任何进一步的连接尝试(通过调用connect()
方法)都会抛出SocketException
。
打印SocketException
的消息以验证以下内容:"already connected"
。
建议:在每次尝试之前创建一个新的Socket
。请注意,对于多个/新连接,Socket
无法重复使用。引自Socket.close()
的Javadoc:
一旦套接字关闭,它就无法用于进一步的网络连接(即无法重新连接或反弹)。需要创建一个新的套接字。