java基于多线程的端口扫描程序
时间: 2023-04-12 13:02:05 浏览: 131
可以使用Java的Socket类和多线程技术来实现端口扫描程序。具体实现可以参考以下代码:
```java
import java.net.*;
import java.util.concurrent.*;
public class PortScanner {
public static void main(String[] args) {
String host = "localhost";
int timeout = 200;
ExecutorService executor = Executors.newFixedThreadPool(20);
for (int port = 1; port <= 65535; port++) {
executor.execute(new PortScannerThread(host, port, timeout));
}
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PortScannerThread implements Runnable {
private String host;
private int port;
private int timeout;
public PortScannerThread(String host, int port, int timeout) {
this.host = host;
this.port = port;
this.timeout = timeout;
}
@Override
public void run() {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
System.out.println("Port " + port + " is open");
socket.close();
} catch (Exception e) {
// ignore
}
}
}
```
这个程序会扫描本地主机的所有端口,如果某个端口是开放的,就会输出"Port [port] is open"。可以根据需要修改host和timeout参数。
阅读全文