Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a socket and then reopen it from the same port in .net

Tags:

c#

.net

sockets

Well, I wonder if some one can help with a problem that I encounter....

I want to close a socket and then rerun from the same port. This is what i am doing...

opening:

    UdpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    UdpServerIpEndPoint = new IPEndPoint(IPAddress.Any, 9050);
    UdpEndPoint = (EndPoint)UdpServerIpEndPoint;
    UdpServer.Bind(UdpServerIpEndPoint);

closeing:

        UdpServer.Shutdown(SocketShutdown.Both);
        UdpServer.Disconnect(true);
        UdpServer.Close();

After I close it. and the I try to reconnect it with the same code as above, I get error:

Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted

I checked for exception during closing, but I didnt get any, i guessed they were closed properly, so actually, what is causing this problem? Please help!

like image 886
Jasim Khan Afridi Avatar asked Oct 30 '11 01:10

Jasim Khan Afridi


Video Answer


1 Answers

I got answer.... I need to use this after decleration of socket...

socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);
like image 163
Jasim Khan Afridi Avatar answered Sep 28 '22 02:09

Jasim Khan Afridi