using System;
using System.Net;
using System.Net.Sockets;
namespace SimplePortForwarding
{
class Program
{
static void Main(string[] args)
{
int localPort = 8080; // 本地端口
int remotePort = 80; // 远程端口
string remoteHost = "http://example.com"; // 远程主机地址
IPAddress localAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0]; // 获取本地IP地址
TcpListener listener = new TcpListener(localAddress, localPort); // 监听本地端口
listener.Start(); // 启动监听器
Console.WriteLine("Listening on {0}:{1}...", localAddress, localPort);
while (true)
{
TcpClient client = listener.AcceptTcpClient(); // 接受客户端连接
Console.WriteLine("Accepted connection from {0}", client.Client.RemoteEndPoint);
NetworkStream stream = client.GetStream(); // 获取网络流
TcpClient remoteClient = new TcpClient(remoteHost, remotePort); // 连接远程主机
Console.WriteLine("Connected to {0}:{1}", remoteHost, remotePort);
NetworkStream remoteStream = remoteClient.GetStream(); // 获取远程网络流
Console.WriteLine("Forwarding data...");
ForwardData(stream, remoteStream); // 转发数据
client.Close(); // 关闭客户端连接
remoteClient.Close(); // 关闭远程主机连接
}
}
static void ForwardData(NetworkStream source, NetworkStream destination)
{
byte[] buffer = new byte[4096]; // 缓冲区
int bytesRead;
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) // 从源流读取数据
{
destination.Write(buffer, 0, bytesRead); // 写入目标流
}
}
}
}