C port forwarding usage details

  • 2021-01-06 00:42:45
  • OfStack

This article illustrates the use of C# port forwarding. Share to everybody for everybody reference. The specific analysis is as follows:

Take link 3389 as an example

Example 1: Port 3389 on an a machine cannot be connected because of a firewall or gateway that restricts access to specific ports such as 80 on an a machine.

Example 2: a machine is not connected to almost all ports (the other side is internal network or firewall gateway restrictions), only 1433, but the other side can connect to some of your ports.


The first kind is simpler, only need the program to open 80 in the other side, you connect him 80, the program received data, sent to his local 3389, at the same time from his 3389 received data after returning to you. The program is a relay station.

using System;
using System.Net.Sockets;
using System.Threading;
namespace PortTransponder
  class Program
    static void Main(string[] args)
      TcpListener tl = new TcpListener(80);
// Open ports that you can connect to and that are not in use 
      while (true)
// You have to use a loop here. You can accept more than 1 A customer 
// Because I find terminal service sometimes 1 If the port does not work, change 1 Reconnect the ports 
// Here's what it means 1 Once the program receives the packet you sent, it will open immediately 2 Threads do transit 
          TcpClient tc1 = tl.AcceptTcpClient();
// This is waiting for the data before executing the next one, no 100% Take up cpu
          TcpClient tc2 = new TcpClient("localhost", 3389);
          tc1.SendTimeout = 300000;
// Set a timeout, otherwise the port will 1 Straight to be occupied, even if the connection is lost 
          tc1.ReceiveTimeout = 300000;
          tc2.SendTimeout = 300000;
          tc2.ReceiveTimeout = 300000;
          object obj1 = (object)(new TcpClient[] { tc1, tc2 });
          object obj2 = (object)(new TcpClient[] { tc2, tc1 });
          ThreadPool.QueueUserWorkItem(new WaitCallback(transfer), obj1);
          ThreadPool.QueueUserWorkItem(new WaitCallback(transfer), obj2);
        catch { }
    public static void transfer(object obj)
      TcpClient tc1 = ((TcpClient[])obj)[0];
      TcpClient tc2 = ((TcpClient[])obj)[1];
      NetworkStream ns1 = tc1.GetStream();
      NetworkStream ns2 = tc2.GetStream();
      while (true)
// There must be try catch , or connect 1 Once interrupted, the program crashed 
// If the pop-up error message for owner to see that � 
          byte[] bt = new byte[10240];
          int count = ns1.Read(bt, 0, bt.Length);
          ns2.Write(bt, 0, count);

I hope this article is helpful to your C# program design.

Related articles: