多线程扫描udp,TCP端口java
时间: 2023-07-10 10:21:16 浏览: 172
可以使用Java的多线程和UDP/TCP协议来实现扫描UDP/TCP端口。以下是一个简单的示例代码:
```java
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
public class PortScanner {
public static void main(String[] args) {
int startPort = 1;
int endPort = 65535;
String ipAddress = "127.0.0.1";
// Scan UDP ports
for(int port = startPort; port <= endPort; port++) {
Runnable udpScanner = new UDPPortScanner(ipAddress, port);
Thread udpThread = new Thread(udpScanner);
udpThread.start();
}
// Scan TCP ports
for(int port = startPort; port <= endPort; port++) {
Runnable tcpScanner = new TCPPortScanner(ipAddress, port);
Thread tcpThread = new Thread(tcpScanner);
tcpThread.start();
}
}
static class UDPPortScanner implements Runnable {
private String ipAddress;
private int port;
public UDPPortScanner(String ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket();
socket.connect(ipAddress, port);
socket.close();
System.out.println("UDP port " + port + " is open");
} catch (SocketException e) {
// port is closed or an error occurred
}
}
}
static class TCPPortScanner implements Runnable {
private String ipAddress;
private int port;
public TCPPortScanner(String ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
@Override
public void run() {
try {
Socket socket = new Socket(ipAddress, port);
socket.close();
System.out.println("TCP port " + port + " is open");
} catch (IOException e) {
// port is closed or an error occurred
}
}
}
}
```
该代码会启动多个线程,每个线程扫描一个UDP/TCP端口。如果端口是开放的,它将输出一条消息。请注意,该示例代码只是一个简单的示例,实际应用中可能需要更多的优化和错误处理。
阅读全文