奇怪的closesocket()行为 [英] Strange closesocket() behavior

查看:226
本文介绍了奇怪的closesocket()行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调用 closesocket()时注意到一个奇怪的行为。如果我创建一个线程调用 recv(),然后 closesocket()会发送 RST 数据包到另一端。但是,如果我不创建一个接收线程, closesocket()将执行一个正常的断开连接(4次握手)。

I have noticed a strange behavior when calling closesocket(). If I create a thread that calls recv(), then closesocket() would send an RST packet to the other side. However, if I do not create a receive thread then closesocket() would perform a graceful disconnection (4-way handshake).

以下代码将使 closesocket()发送 RST 数据包:

The following code will cause closesocket() to send an RST packet:

#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#include <process.h>

unsigned int __stdcall thread(void *s)
{
    char buffer[1024];
    recv((SOCKET)s, buffer, 1024, 0);

    return 0;
}

int main()
{
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
    SOCKET s = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("173.194.116.18");
    addr.sin_port = htons(80);
    connect(s, (sockaddr*)&addr, sizeof(addr));

    // Start thread
    _beginthreadex(0, 0, thread, (void*)s, 0, 0);
    Sleep(1000); // give thread some time to start

    // RST packet will be sent (if you remove the receive thread then a graceful disconnection will be performed)
    closesocket(s);

    return 0;
}

注意:我使用阻止套接字。 / p>

Note: I am using blocking sockets.

推荐答案

如果
客户端发送多个字节,服务器将读取第一个字节并调用close接收队列,使得RST被发送到客户端。调用recv()等待来自
服务器的响应时,客户端将被阻止。收到RST后,DieWithError()报告连接由对等端复位的问题。
所以关闭可以在调用close之前使用。
我希望本文将帮助您了解相关的RST http:/ /cs.ecs.baylor.edu/~donahoo/practical/CSockets/TCPRST.pdf

这篇关于奇怪的closesocket()行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆