dermesser / libsocket

The ultimate socket library for C and C++, supporting TCP, UDP and Unix sockets (DGRAM and STREAM) on Linux, FreeBSD, Solaris. See also my uvco library for a refreshed version!
https://borgac.net/~lbo/doc/libsocket/
Other
797 stars 195 forks source link

"Address already in use" issue #61

Closed AndreasAakerberg closed 5 years ago

AndreasAakerberg commented 5 years ago

I keep getting the "Address already in use" error when trying to create an inet stream server using an addr/port combination that has been previously used. Here are the steps to recreate the issue: 1: Create an inet_stream_server as described in server.cpp example using the SO_REUSEADDR flag. 2: Connect a client to the server. 3: Destroy the server (returns without errors)

Repeating step 1 using the same addr/port combination as prev. used causes the aforementioned error,

Any advice?

Thanks

dermesser commented 5 years ago

I only know that it has happened to me as well, especially when Ctrl-C'ing a running server. I do not know why, but suspect that it is due to existing sockets in TIME_WAIT state (or similar), waiting for packets to arrive. It may help to try closing sockets first, e.g. by catching signals, but I don't have a much better solution.

AndreasAakerberg commented 5 years ago

Thank you for your input, I will see if I can find a workaround.

dermesser commented 5 years ago

Apparently you can tune this using sysctls:

# Decrease TIME_WAIT seconds
net.ipv4.tcp_fin_timeout = 30

# Recycle and Reuse TIME_WAIT sockets faster
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1