.Net Development


.Net Development19 Jul 2011 08:39 pm

If you are doing low level TCP networking in .Net and in particular are using a TcpListener on a client to listen for callbacks form a server, you need to select a port on which to listen. Typically, in this scenario, you don’t want to have to specify a port in the .config file. You just want to pick any open port (well actually, any open port, in the IANA private port range).

After looking around the net, I found some almost correct but not quite code for this, so I though I should post my improved version here.

The below function will return the first open port in the IANA port range that is not currently being used on the local machine.

Be careful however. Just because the port is not used at the point the code is called, doesn’t mean it won’t be in use when you go to open your listener. Just incase some other process grabbed the port in the interim, you should always open your listener in a try catch block and if the call fails because the port is in use, grab another available port and try again.

private static int SelectAvailablePort()
{
    const int START_OF_IANA_PRIVATE_PORT_RANGE = 49152;
    var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    var tcpListeners = ipGlobalProperties.GetActiveTcpListeners();
    var tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
 
    var allInUseTcpPorts = tcpListeners.Select(tcpl => tcpl.Port)
        .Union(tcpConnections.Select(tcpi => tcpi.LocalEndPoint.Port));
 
    var orderedListOfPrivateInUseTcpPorts = allInUseTcpPorts
        .Where(p => p >= START_OF_IANA_PRIVATE_PORT_RANGE)
        .OrderBy(p => p);
 
    var candidatePort = START_OF_IANA_PRIVATE_PORT_RANGE;
    foreach (var usedPort in orderedListOfPrivateInUseTcpPorts)
    {
        if (usedPort != candidatePort) break;
        candidatePort++;
    }
    return candidatePort;
}

Disclaimer: I am by no means an network programming guru. If you find issues with this snippet or have a better one, please let me know.

.Net Development&Automated Testing10 Jun 2011 10:10 pm

I just found this gem in a post on another subject on Krzysztof Koźmic’s blog and thought it merited its own post. Beautifully simply solution for asserting that a class doesn’t hold a reference to an object that it should not.

[Fact]
public void Freezable_should_not_hold_any_reference_to_created_objects()
{
    var pet = Freezable.MakeFreezable<Pet>();
    var petWeakReference = new WeakReference(pet, false);
    pet = null;
    GC.Collect();
    Assert.False(petWeakReference.IsAlive, "Object should have been collected");
}
.Net Development02 Apr 2011 07:26 am

This is just a quick plug for a post on Jim Christopher’s blog, beefycode.com, that explains how to create a Unity Extension to support IoC Chaining in much the same way as Castle Windsor does. I am going to need this someday and don’t want to loose the link. Thanks Jim.

« Previous PageNext Page »