原文在这里:http://bbs.chinaunix.net/thread-930153-1-1.html
link: http://libsbase.googlecode.com/svn/trunk/0.0.2/netcheck-0.0.3.tar.gz
- /* Net check Make sure you have not used OUT OF BAND DATA AND YOU CAN use OOB */
- int netcheck(int fd)
- {
- int buf_size = 1024;
- char buf[buf_size];
- //clear OOB DATA
- recv(fd, buf, buf_size);
- if(send(fd, (void *)"\0", 1, MSG_OOB) < 0 )
- {
- fprintf(stderr, "Connection[%d] send OOB failed, %s", fd, strerror(errno));
- return -1;
- }
- return 0;
- }
- /* Setting SO_TCP KEEPALIVE */
- //int keep_alive = 1;//设定KeepAlive
- //int keep_idle = 1;//开始首次KeepAlive探测前的TCP空闭时间
- //int keep_interval = 1;//两次KeepAlive探测间的时间间隔
- //int keep_count = 3;//判定断开前的KeepAlive探测次数
- void set_keepalive(int fd, int keep_alive, int keep_idle, int keep_interval, int keep_count)
- {
- int opt = 1;
- if(keep_alive)
- {
- if(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
- (void*)&keep_alive, sizeof(keep_alive)) == -1)
- {
- fprintf(stderr,
- "setsockopt SOL_SOCKET::SO_KEEPALIVE failed, %s\n",strerror(errno));
- }
- if(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE,
- (void *)&keep_idle,sizeof(keep_idle)) == -1)
- {
- fprintf(stderr,
- "setsockopt SOL_TCP::TCP_KEEPIDLE failed, %s\n", strerror(errno));
- }
- if(setsockopt(fd,SOL_TCP,TCP_KEEPINTVL,
- (void *)&keep_interval, sizeof(keep_interval)) == -1)
- {
- fprintf(stderr,
- "setsockopt SOL_tcp::TCP_KEEPINTVL failed, %s\n", strerror(errno));
- }
- if(setsockopt(fd,SOL_TCP,TCP_KEEPCNT,
- (void *)&keep_count,sizeof(keep_count)) == -1)
- {
- fprintf(stderr,
- "setsockopt SOL_TCP::TCP_KEEPCNT failed, %s\n", strerror(errno));
- }
- }
- }