Xiao-Bin Ma
Xiao-Bin Ma

Reputation: 3

Why TCP client can not connect to TCP server sometimes after TCP server restart?

I just wrote a TCP server and it worked fine most of the time. But if I kill it manually and restart it immediately, TCP client could not connect to it sometimes. Then if I kill it and restart it again, it will be okay again. I really want to know why and I had try to modify /proc/sys/net/ipv4/tcp_tw_recycle and /proc/sys/net/ipv4/tcp_tw_reuse. But it didn't work.

Upvotes: 0

Views: 2083

Answers (1)

julumme
julumme

Reputation: 2366

This has indeed to do with the way sockets are set to be re-used.

Try initializing your socket in this way:

int reuse_addr = 1;
int listener_socket = 0;

listener_socket = socket(AF_INET, SOCK_STREAM, 0); //get socket handle
if (listener_socket < 0)
{
  //Handle error
}

//Set the socket reusable
setsockopt(listener_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(int));

Variable reuse_addr is 1 to identify that we want to enable a particular option (0 will disable).

The SOL_SOCKET keyword means that you want to set socket level setting/option, it will be protocol independent. We set SO_REUSEADDR, you can read more about it here: http://www.unixguide.net/network/socketfaq/4.5.shtml

Other available settings, you can check from here: http://www.delorie.com/gnu/docs/glibc/libc_352.html

Upvotes: 1

Related Questions