public virtual void TestBindAddress() { CheckBindAddress("localhost", 0, false).Stop(); // hang onto this one for a bit more testing HttpServer2 myServer = CheckBindAddress("localhost", 0, false); HttpServer2 myServer2 = null; try { int port = myServer.GetConnectorAddress(0).Port; // it's already in use, true = expect a higher port myServer2 = CheckBindAddress("localhost", port, true); // try to reuse the port port = myServer2.GetConnectorAddress(0).Port; myServer2.Stop(); NUnit.Framework.Assert.IsNull(myServer2.GetConnectorAddress(0)); // not bound myServer2.OpenListeners(); Assert.Equal(port, myServer2.GetConnectorAddress(0).Port); } finally { // expect same port myServer.Stop(); if (myServer2 != null) { myServer2.Stop(); } } }
/// <exception cref="System.Exception"/> private HttpServer2 CheckBindAddress(string host, int port, bool findPort) { HttpServer2 server = CreateServer(host, port); try { // not bound, ephemeral should return requested port (0 for ephemeral) IList <object> listeners = (IList <object>)Whitebox.GetInternalState(server, "listeners" ); Connector listener = (Connector)listeners[0]; Assert.Equal(port, listener.GetPort()); // verify hostname is what was given server.OpenListeners(); Assert.Equal(host, server.GetConnectorAddress(0).GetHostName() ); int boundPort = server.GetConnectorAddress(0).Port; if (port == 0) { Assert.True(boundPort != 0); } else { // ephemeral should now return bound port if (findPort) { Assert.True(boundPort > port); // allow a little wiggle room to prevent random test failures if // some consecutive ports are already in use Assert.True(boundPort - port < 8); } } } catch (Exception e) { server.Stop(); throw; } return(server); }