Created
January 5, 2018 02:15
-
-
Save kg/09f6eeb8082838913a65eb5b19fbb9d6 to your computer and use it in GitHub Desktop.
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; | |
public static class Program { | |
public static void Main () { | |
while (true) { | |
Step(); | |
// Even though we're closing our listener and sockets, without this we run out of files in Mono on Linux | |
// GC.Collect(); | |
} | |
} | |
const int FirstPort = 4010; | |
const int LastPort = 4040; | |
static int Port = FirstPort; | |
public static void Step () { | |
// listen with a new listener (IPv4 is the default) | |
TcpListener inListener = new TcpListener (Port); | |
inListener.Start(); | |
// connect to it from a new socket | |
IPHostEntry hostent = Dns.GetHostByAddress (IPAddress.Loopback); | |
Socket outSock = null; | |
foreach (IPAddress address in hostent.AddressList) { | |
if (address.AddressFamily != AddressFamily.InterNetwork) | |
continue; | |
/// Only keep IPv4 addresses, our Server is in IPv4 only mode. | |
outSock = new Socket ( | |
address.AddressFamily, SocketType.Stream, | |
ProtocolType.IP | |
); | |
IPEndPoint remote = new IPEndPoint (address, Port); | |
outSock.Connect (remote); | |
break; | |
} | |
if (!inListener.Pending()) { | |
Thread.Sleep(50); | |
if (!inListener.Pending()) | |
Console.Write("!"); | |
else | |
Console.Write(","); | |
} else { | |
Console.Write("."); | |
} | |
Socket inSock = inListener.AcceptSocket (); | |
// tidy up after ourselves | |
inSock.Close (); | |
outSock.Close (); | |
// This quietly leaks a socket handle | |
inListener.Stop (); | |
Port += 1; | |
if (Port > LastPort) | |
Port = FirstPort; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment