In my project I have a class that checks all ports at localhost and returns true if port is free and false if it is not. The solution is based on this answer
I need somehow to test it. Is there a way to temporarily use the port and then to free it back?
I've tried to use TcpListener Start with no success. If I use TcpClient Connect I get System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 127.0.0.1:myPort.
Here's the code I use:
class TestPortLocker
{
public TcpClient client;
public TcpListener listener;
public void Lock(int port)
{
client = new TcpClient();
client.Connect("localhost", port);
//listener = new TcpListener(port);
//listener.Start();
}
public void Stop()
{
client.Close();
//listener.Stop();
}
}