Created
November 13, 2014 02:09
-
-
Save anonymous/03a3eaafd6839236dcc4 to your computer and use it in GitHub Desktop.
TCP Hole Punching
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.Linq; | |
using System.Net.Sockets; | |
using System.Net; | |
namespace TCPPunch | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
if (args.Count() != 3) | |
{ | |
Console.WriteLine("Incorrect args"); | |
} | |
var remote_endpoint = new IPEndPoint(IPAddress.Parse(args[0]), int.Parse(args[1])); | |
var local_endpoint = new IPEndPoint(IPAddress.Any, int.Parse(args[2])); | |
Console.WriteLine("Punching hole..."); | |
using (var outgoing = new TcpClient(local_endpoint)) | |
{ | |
try | |
{ | |
outgoing.Connect(remote_endpoint); | |
Console.WriteLine("Made outgoing connection. Exiting."); | |
return; | |
} | |
catch (Exception ex) | |
{ | |
if (!(ex.Message.StartsWith("No connection could be made because the target machine actively refused it") || ex.Message.StartsWith("A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"))) | |
throw; | |
} | |
} | |
Console.WriteLine("Hole should be punched"); | |
var l = new TcpListener(local_endpoint); | |
l.Start(); | |
using (l.AcceptTcpClient()) | |
{ | |
Console.WriteLine("Recieve connection"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment