Created
September 14, 2014 06:12
-
-
Save tvolodimir/e36cc9c086934b127526 to your computer and use it in GitHub Desktop.
tcp proxy
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; | |
using System.Threading; | |
namespace Proxy | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int localPort = int.Parse(args[0]); | |
int openPort = int.Parse(args[1]); | |
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
listener.Bind(new IPEndPoint(IPAddress.Any, openPort)); | |
listener.Listen(10); | |
while (true) | |
{ | |
var c = listener.Accept(); | |
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
s.Connect(new IPEndPoint(IPAddress.Loopback, localPort)); | |
Thread serverThread = new Thread(o => | |
{ | |
byte[] stuff = new byte[1024]; | |
try | |
{ | |
while (true) | |
{ | |
int count = s.Receive(stuff); | |
if (count == 0) | |
{ | |
s.Close(); | |
return; | |
} | |
c.Send(stuff, count, SocketFlags.None); | |
} | |
} | |
catch (Exception) | |
{ | |
s.Close(); | |
c.Close(); | |
} | |
}); | |
Thread clientThread = new Thread(o => | |
{ | |
try | |
{ | |
byte[] stuff = new byte[1024]; | |
try | |
{ | |
while (true) | |
{ | |
int count = c.Receive(stuff); | |
if (count == 0) | |
{ | |
c.Close(); | |
return; | |
} | |
s.Send(stuff, count, SocketFlags.None); | |
} | |
} | |
catch (Exception) | |
{ | |
s.Close(); | |
c.Close(); | |
} | |
} | |
catch (Exception) | |
{ | |
} | |
}); | |
serverThread.Start(); | |
clientThread.Start(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment