Skip to content

Instantly share code, notes, and snippets.

@bongbongco
Created August 25, 2016 02:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bongbongco/588abf3928cbd297443dd9da8171eb9a to your computer and use it in GitHub Desktop.
Save bongbongco/588abf3928cbd297443dd9da8171eb9a to your computer and use it in GitHub Desktop.
C# Port Forwarding
using System;
using System.Net;
using System.Net.Sockets;
namespace BrunoGarcia.Net
{
public class TcpForwarderSlim
{
private readonly Socket _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public void Start(IPEndPoint local, IPEndPoint remote)
{
_mainSocket.Bind(local);
_mainSocket.Listen(10);
while (true)
{
var source = _mainSocket.Accept();
var destination = new TcpForwarderSlim();
var state = new State(source, destination._mainSocket);
destination.Connect(remote, source);
source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
private void Connect(EndPoint remoteEndpoint, Socket destination)
{
var state = new State(_mainSocket, destination);
_mainSocket.Connect(remoteEndpoint);
_mainSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state);
}
private static void OnDataReceive(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
var bytesRead = state.SourceSocket.EndReceive(result);
if (bytesRead > 0)
{
state.DestinationSocket.Send(state.Buffer, bytesRead, SocketFlags.None);
state.SourceSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
catch
{
state.DestinationSocket.Close();
state.SourceSocket.Close();
}
}
private class State
{
public Socket SourceSocket { get; private set; }
public Socket DestinationSocket { get; private set; }
public byte[] Buffer { get; private set; }
public State(Socket source, Socket destination)
{
SourceSocket = source;
DestinationSocket = destination;
Buffer = new byte[8192];
}
}
}
}
@Alexandr-baryshev
Copy link

Alexandr-baryshev commented Mar 19, 2022

This code helped me a lot, thanks!
Can you please tell me how to close the socket?

The method below didn't work for me..(

    public void Stop()
    {
        try
        {
            _mainSocket.Shutdown(SocketShutdown.Both);
        }
        finally
        {
            _mainSocket.Close();
        }
    }

@2kingz
Copy link

2kingz commented Jul 21, 2022

Hie i need help. i want to forward my Xampp port using C#, how can i do that. i am new to coding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment