How to "unbind" a socket programmatically?

21,063

I suspect you are confusing the sockets of your connected clients with your server socket.

Your server socket is the one listening for incoming connections on a specific port. The socket you close in that function is your pipe to one of (potentially many) remote connections.

To "unbind the port", you'll want to Shutdown/Close the server socket.

Update to clear some confusion

You should have a "server" socket that you made a call to .Bind(EndPoint) on, followed by a call to .Listen(). This is the socket you want to Shutdown/Close to "unbind" and free up a port for later.

You then have multiple "client" sockets that you get references to whenever your "server" socket accepts a new connection. These can all be bound to the same port without problem. To close one of these connections and disconnect your client, do what you're doing now. You can actually trim the method down to:

  • Shutdown
  • Close
  • Remove from your list

Disconnect and the rest are unnecessary.

Share:
21,063
ryan1894
Author by

ryan1894

Updated on January 07, 2020

Comments

  • ryan1894
    ryan1894 over 4 years

    1) The socket doesn't seem to unbind from the LocalEndPoint until the process ends.
    2) I have tried the solutions from the other question, and also tried waiting a minute - to no avail.
    3) At the moment I have tried the below to get rid of the socket and its connections:

    public static void killUser(User victim)  
        {  
            LingerOption lo = new LingerOption(false, 0);  
    victim.connectedSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Linger,     lo);  
            victim.connectedSocket.Shutdown(SocketShutdown.Both);  
            victim.connectedSocket.Disconnect(true);  
            victim.connectedSocket.Close();  
            clients.RemoveAt(victim.ID);  
        }  
    

    4) After a bit of googling, I can't seem to be able to unbind a port, thus if I have a sufficient amount of connecting clients, I will eventually run out of ports to listen on.