2009年12月25日 星期五

socket keep alive time

You might know that,while setting up a TCP connection you can enable SO_KEEPALIVE, forcing the system to check on the connection routinely to see if the connection is still there, not broken by the any connection issues or so.
Yet, have you ever wondered, how often does the system go through this connection check?
This is how we change "keep alive time" for individual socket on linux systems, otherwise the system checks for the connection every 30 mins or so, by default, which is usually too long.
Notice: this is not a standard socket operation, which may not be used on other operating systems. (for example: windows)
Code:
int keepAlive = 1;

// set timeout params for SO_KEEPALIVE
keepTime = 5; //the interval between the last data packet sent (simple ACKs are not considered data) and the first keepalive probe
keepProbe = 1; //number of retry
keepInvl = 1; //the interval between subsequential keepalive probes, regardless of what the connection has exchanged in the meantime
if( setsockopt(cliSocket, SOL_TCP, TCP_KEEPIDLE, &keepTime, sizeof(keepTime)) == -1
||setsockopt(cliSocket, SOL_TCP, TCP_KEEPCNT, &keepProbe, sizeof(keepProbe)) == -1
||setsockopt(cliSocket, SOL_TCP, TCP_KEEPINTVL, &keepInvl, sizeof(keepInvl)) == -1
||setsockopt(cliSocket,SOL_SOCKET,SO_KEEPALIVE, &keepAlive,sizeof(keepAlive)) == -1)
{
printf("Socket %d setKeepAlive timeout failed.\n", cliSocket);
close(cliSocket);
}

沒有留言: