如何在.NET上创建软件路由器?

时间:2013-03-31 09:49:47

标签: c# .net windows sockets ports

如何创建一个透明地转发到新IP地址/端口的连接的程序?

例如,如果客户端启动TCP连接,IP地址为111.111.111.111,TCP端口为111,则可以将程序配置为转发该数据包和IP /端口222.222.222.222:222。

透明地,我的意思是:

  • 最低性能损失
  • 无需调整客户端或最终目标软件/配置(就像透明Web代理不需要在浏览器中设置显式设置一样)
  • 与OS网络层交易尽可能低级别

我想用.NET,C#和Windows来做这件事。但我不想创建一个简单的TCP代理,因为各种各样但未指明的原因。如果无法做到这一点,那么在没有可能的解决方案的情况下,这可能是一个可接受的答案。

1 个答案:

答案 0 :(得分:7)

这是我几周前写的一个实验:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Globalization;
using System.Threading;

namespace TcpTunnel {

public static class Program {

    public static void Main(String[] args) {

        if( args.Length != 3 ) {

            Console.WriteLine("<remoteAddress> <remotePort> <listenPort>");
            return;
        }

        ServerConfiguration config;

        try {

            config = new ServerConfiguration( args[0], args[1], args[2] );

        } catch(ArgumentException aex) {

            Console.WriteLine("<remoteAddress> <remotePort> <listenPort>");
            Console.WriteLine( aex.Message );
            return;
        }

        Thread serverThread = new Thread( ServerThread );
        serverThread.Start( config );

        Console.WriteLine("Enter \"q<enter>\" to stop program.");

        String line;
        while( (line = Console.ReadLine()).ToUpperInvariant() != "Q" );

        config.ServerSocket.Shutdown(SocketShutdown.Both);
        config.ServerSocket.Close();
    }

    private class ServerConfiguration {

        public IPAddress RemoteAddress;
        public UInt16    RemotePort;
        public UInt16    ListenPort;

        public ServerConfiguration(String remoteAddress, String remotePort, String listenPort) {

            RemoteAddress = IPAddress.Parse( remoteAddress );
            RemotePort    = UInt16   .Parse( remotePort, NumberStyles.Integer, CultureInfo.InvariantCulture );
            ListenPort    = UInt16   .Parse( listenPort, NumberStyles.Integer, CultureInfo.InvariantCulture );
        }

        public Boolean RunServer = true;

        public Socket  ServerSocket;
    }

    private static void ServerThread(Object configObj) {

        ServerConfiguration config = (ServerConfiguration)configObj;

        ///////////////////////////////////////
        // Setup  



        ///////////////////////////////////////
        // Wait for client

        Socket serverSocket = config.ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Unspecified);

        serverSocket.Bind( new IPEndPoint( IPAddress.Any, config.ListenPort ) );
        serverSocket.Listen(1);

        Console.WriteLine("Now listening for port {0}, will forward to {1}.", config.ListenPort, config.RemotePort);

        while( config.RunServer ) {

            Socket client = serverSocket.Accept();

            Thread clientThread = new Thread( ClientThread );
            clientThread.Start( new ClientContext() { Config = config, Client = client } );
        }

    }

    private class ClientContext {

        public ServerConfiguration Config;
        public Socket              Client;
    }

    private static void ClientThread(Object contextObj) {

        ClientContext context = (ClientContext)contextObj;

        Socket              client = context.Client;
        ServerConfiguration config = context.Config;

        ///////////////////////////////////////
        // Connect to remote server.

        IPEndPoint remoteEndPoint = new IPEndPoint( config.RemoteAddress, config.RemotePort );

        Socket remote = new Socket( remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);

        remote.Connect( remoteEndPoint );

        ///////////////////////////////////////
        // Run tunnel.

        Console.WriteLine("Running tunnel.");

        Byte[] buffer = new Byte[4096];

        for(;;) {

            if( client.Available > 0 ) {

                Int32 count = client.Receive( buffer );
                if( count == 0 ) return;

                remote.Send( buffer, count, SocketFlags.None );
            }

            if( remote.Available > 0 ) {

                Int32 count = remote.Receive( buffer );
                if( count == 0 ) return;

                client.Send( buffer, count, SocketFlags.None );
            }
        }
    }

}

}