SoFunction
Updated on 2025-03-06

Detailed explanation of the usage of C# port forwarding

This article describes the usage of C# port forwarding. Share it for your reference. The specific analysis is as follows:

Here is an example when link 3389 is

Example 1: The 3389 port connected to machine a cannot be connected because the other party's firewall or gateway has restricted it, and can only access individual ports of machine a, such as 80.

Example 2: Almost all ports connected to a machine cannot be connected to (the other party has restricted the intranet or firewall gateway), and can only go up 1433, but the other party can connect to some of your ports.

Solution:

The first type is simpler. You only need the program to open 80 on the other party. You connect it to 80. After the program receives the data, it sends it to 3389 of its native machine, and returns it to you after receiving the data from 3389. The program is a transit station.

using System;
using ;
using ;
namespace PortTransponder
{
  class Program
  {
    static void Main(string[] args)
    {
      TcpListener tl = new TcpListener(80);
//Open the port that the other party can be connected to and not occupied here.      ();
      while (true)
//The loop must be used here, which can receive more than one customer//Because I found that sometimes the terminal service does not work, so I change the port and reconnect it.      {
//The following means that once the program receives the data packet you sent, it immediately opens 2 threads to transfer.        try
        {
          TcpClient tc1 = ();
//This is waiting for the data to be executed below, and it will not occupy 100% of the CPU          TcpClient tc2 = new TcpClient("localhost", 3389);
           = 300000;
//Set timeout, otherwise the port will be occupied, even if the connection is lost           = 300000;
           = 300000;
           = 300000;
          object obj1 = (object)(new TcpClient[] { tc1, tc2 });
          object obj2 = (object)(new TcpClient[] { tc2, tc1 });
          (new WaitCallback(transfer), obj1);
          (new WaitCallback(transfer), obj2);
        }
        catch { }
      }
    }
    public static void transfer(object obj)
    {
      TcpClient tc1 = ((TcpClient[])obj)[0];
      TcpClient tc2 = ((TcpClient[])obj)[1];
      NetworkStream ns1 = ();
      NetworkStream ns2 = ();
      while (true)
      {
        try
        {
//There must be try catch here, otherwise the connection will crash once the program is interrupted//If an error message pops up and lets the owner see it, it will be embarrassing          byte[] bt = new byte[10240];
          int count = (bt, 0, );
          (bt, 0, count);
        }
        catch
        {
          ();
          ();
          ();
          ();
          break;
        }
      }
    }
  }
}

I hope this article will be helpful to everyone's C# programming.