您的位置:首页 > 运维架构 > Linux

完全实现linux下SOCKET连接断开判断

2014-01-14 08:20 555 查看
原文在这里: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)

   
4000
             {

                        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));

                }

        }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: