safe close tcp connection

 

https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable

http://stackoverflow.com/questions/8874021/close-socket-directly-after-send-unsafe

 

发送端代码

    sock = socket(AF_INET, SOCK_STREAM, 0);  
    connect(sock, &remote, sizeof(remote));
    write(sock, buffer, 1000000);             // returns 1000000
    shutdown(sock, SHUT_WR);
  // 最后这一步要加个超时,防止接收端恶意发送数据 for(;;) { res=read(sock, buffer, 4000); if(res < 0) { perror("reading"); exit(1); } if(!res) break; } close(sock);

这么做的原因是

1. send 成功只是把数据放到了内核的发送缓冲区

2. 当调用 close 时,如果 TCP 的接收缓冲区内有数据,会导致发送 RST(而不是 FIN),并清空发送缓冲区。

 

最好接收端在应用层返回 ack 给发送端。TCP 并不是绝对可靠的

 

posted on 2017-01-08 22:44  明天有风吹  阅读(360)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园