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

来源:互联网 发布:网络思想政治教育论文 编辑:程序博客网 时间:2024/06/15 20:42
  1. /* Net check Make sure you have not used OUT OF BAND DATA AND YOU CAN use OOB */
  2. int netcheck(int fd) 
  3. {
  4.         int buf_size = 1024;
  5.         char buf[buf_size];
  6.         //clear OOB DATA 
  7.         recv(fd, buf, buf_size);
  8.         if(send(fd, (void *)"\0", 1, MSG_OOB) < 0 )
  9.         {
  10.                 fprintf(stderr, "Connection[%d] send OOB failed, %s", fd, strerror(errno));
  11.                 return -1;
  12.         }
  13.         return 0;
  14. }
复制代码

  1. /* Setting SO_TCP KEEPALIVE */
  2. //int keep_alive = 1;//设定KeepAlive
  3. //int keep_idle = 1;//开始首次KeepAlive探测前的TCP空闭时间
  4. //int keep_interval = 1;//两次KeepAlive探测间的时间间隔
  5. //int keep_count = 3;//判定断开前的KeepAlive探测次数
  6. void set_keepalive(int fd, int keep_alive, int keep_idle, int keep_interval, int keep_count)
  7. {
  8.         int opt = 1;
  9.         if(keep_alive)
  10.         {
  11.                 if(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
  12.                                         (void*)&keep_alive, sizeof(keep_alive)) == -1)
  13.                 {
  14.                         fprintf(stderr, 
  15.                                 "setsockopt SOL_SOCKET::SO_KEEPALIVE failed, %s\n",strerror(errno));
  16.                 }
  17.                 if(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE,
  18.                                         (void *)&keep_idle,sizeof(keep_idle)) == -1)
  19.                 {
  20.                         fprintf(stderr,
  21.                                 "setsockopt SOL_TCP::TCP_KEEPIDLE failed, %s\n", strerror(errno));
  22.                 }
  23.                 if(setsockopt(fd,SOL_TCP,TCP_KEEPINTVL,
  24.                                         (void *)&keep_interval, sizeof(keep_interval)) == -1)
  25.                 {
  26.                         fprintf(stderr,
  27.                                  "setsockopt SOL_tcp::TCP_KEEPINTVL failed, %s\n", strerror(errno));
  28.                 }
  29.                 if(setsockopt(fd,SOL_TCP,TCP_KEEPCNT,
  30.                                         (void *)&keep_count,sizeof(keep_count)) == -1)
  31.                 {
  32.                         fprintf(stderr, 
  33.                                 "setsockopt SOL_TCP::TCP_KEEPCNT failed, %s\n", strerror(errno));
  34.                 }
  35.         }
  36. }
原创粉丝点击