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); // 監(jiān)聽本地端口
listener.Start(); // 啟動監(jiān)聽器
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(); // 獲取網(wǎng)絡流
TcpClient remoteClient = new TcpClient(remoteHost, remotePort); // 連接遠程主機
Console.WriteLine("Connected to {0}:{1}", remoteHost, remotePort);
NetworkStream remoteStream = remoteClient.GetStream(); // 獲取遠程網(wǎng)絡流
Console.WriteLine("Forwarding data...");
ForwardData(stream, remoteStream); // 轉(zhuǎn)發(fā)數(shù)據(jù)
client.Close(); // 關(guān)閉客戶端連接
remoteClient.Close(); // 關(guān)閉遠程主機連接
}
}
static void ForwardData(NetworkStream source, NetworkStream destination)
{
byte[] buffer = new byte[4096]; // 緩沖區(qū)
int bytesRead;
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) // 從源流讀取數(shù)據(jù)
{
destination.Write(buffer, 0, bytesRead); // 寫入目標流
}
}
}
}