UDP socket still bound to previous port – how to reuse it?

I have an audio streaming application that uses boost UDP sockets bound to port 50050. I currently have a problem when the application is shut down while streaming. When restarting the app it cannot bind to port 50050 anymore. I did a "netstat -p UDP" and it shows me the following

Proto Recv-Q Send-Q Local Address Foreign Address (state)

udp4 1026 0 *.50050 .

So, basically the receive queue for this socket is not empty and the previously bound port is indeed still active.

Now I wonder if a) there is way to force binding to port 50050 or b) the socket receive queue can be cleared or c) the existing socket could be reused or d) if you have other suggestions how to solve the issue ?

Thanks in advance, best

Alex


Solution 1:

Unlike with TCP an UDP socket is not lingering around in some temporary state once the socket is closed by the application. What you see means therefore that there is still a process owning a socket bound to this port. This suggest that the application was not fully shutdown but at least one thread of it is still running. Or it might be a forked child which inherited the socket.

While you can create an additional socket with SO_REUSEADDR (see other comments and answers for details) this will not make the already existing socket inactive. Data send to this port will end up at only one of the existing sockets and will not be propagated to all. This might lead to data loss.

Solution 2:

Set the SO_REUSEADDR property on the socket before invoking bind.

int fAllow = 1;
int result;


result = ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &fAllow, sizeof(fAllow));