java 批量代理端口例子,支持TCP和UDP
时间: 2024-05-15 20:15:31 浏览: 85
以下是一个Java批量代理端口的例子,支持TCP和UDP:
```java
import java.io.IOException;
import java.net.*;
public class PortProxy {
private static final int BUFFER_SIZE = 1024;
private static final int TIMEOUT = 3000;
private int srcPort;
private String dstHost;
private int dstPort;
private boolean isTCP;
public PortProxy(int srcPort, String dstHost, int dstPort, boolean isTCP) {
this.srcPort = srcPort;
this.dstHost = dstHost;
this.dstPort = dstPort;
this.isTCP = isTCP;
}
public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket(srcPort);
while (true) {
Socket socket = serverSocket.accept();
new Thread(() -> {
try {
if (isTCP) {
handleTCP(socket);
} else {
handleUDP(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
private void handleTCP(Socket socket) throws IOException {
Socket dstSocket = new Socket();
dstSocket.connect(new InetSocketAddress(dstHost, dstPort), TIMEOUT);
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = socket.getInputStream().read(buffer)) != -1) {
dstSocket.getOutputStream().write(buffer, 0, len);
dstSocket.getOutputStream().flush();
len = dstSocket.getInputStream().read(buffer);
socket.getOutputStream().write(buffer, 0, len);
socket.getOutputStream().flush();
}
dstSocket.close();
socket.close();
}
private void handleUDP(Socket socket) throws IOException {
DatagramSocket dstSocket = new DatagramSocket();
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = socket.getInputStream().read(buffer)) != -1) {
DatagramPacket packet = new DatagramPacket(buffer, len, InetAddress.getByName(dstHost), dstPort);
dstSocket.send(packet);
packet = new DatagramPacket(buffer, BUFFER_SIZE);
dstSocket.receive(packet);
socket.getOutputStream().write(packet.getData(), 0, packet.getLength());
socket.getOutputStream().flush();
}
dstSocket.close();
socket.close();
}
public static void main(String[] args) throws IOException {
PortProxy tcpProxy = new PortProxy(8080, "localhost", 80, true);
tcpProxy.start();
PortProxy udpProxy = new PortProxy(8081, "localhost", 53, false);
udpProxy.start();
}
}
```
该例子创建了一个`PortProxy`类,用于代理指定端口的TCP或UDP流量。在`main`方法中,我们创建了两个实例分别代理本地8080端口的HTTP流量和本地8081端口的DNS流量。
在`start`方法中,我们使用一个循环不断接受客户端连接,并在新的线程中处理。处理过程中,我们首先连接到目标主机,并将数据从源端口传输到目标端口。对于TCP流量,我们使用`Socket`进行传输;对于UDP流量,我们使用`DatagramSocket`进行传输。
注意,UDP流量需要在传输数据之前先创建一个`DatagramSocket`,并将目标主机和端口封装在`DatagramPacket`中。在传输完数据后,我们需要关闭`DatagramSocket`,否则会一直等待数据到来,导致程序无法退出。
阅读全文