Skip to content

Instantly share code, notes, and snippets.

Created November 13, 2014 02:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/03a3eaafd6839236dcc4 to your computer and use it in GitHub Desktop.
Save anonymous/03a3eaafd6839236dcc4 to your computer and use it in GitHub Desktop.
TCP Hole Punching
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