Created
August 25, 2016 02:48
-
-
Save bongbongco/588abf3928cbd297443dd9da8171eb9a to your computer and use it in GitHub Desktop.
C# Port Forwarding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
} | |
} | |
} |
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
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..(