为什么SO_REUSEADDR让我接管TIME_WAIT中的连接?

时间:2018-03-02 16:20:12

标签: c++ windows winsock

当然,这不是我的实际代码,但它是展示我遇到的问题的最小尺寸示例。

#include<winsock2.h>
#include<ws2tcpip.h>
#include<stdlib.h>
#include<stdio.h>
#pragma comment(lib, "Ws2_32.lib")

int main() {
    bool iOptVal = true;

    WSADATA wsaData = { 0 };
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    SOCKET s1 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    SOCKET s2 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct sockaddr_in local_addr;
    memset(&local_addr, 0, sizeof local_addr);
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
    local_addr.sin_port = htons(52685);

    setsockopt(s1, SOL_SOCKET, SO_REUSEADDR, (char*)&iOptVal, sizeof(bool));
    setsockopt(s2, SOL_SOCKET, SO_REUSEADDR, (char*)&iOptVal, sizeof(bool));

    bind(s1, (sockaddr *)&local_addr, sizeof(local_addr));
    printf("bind(s1) returned error %d\n", WSAGetLastError());

    bind(s2, (sockaddr *)&local_addr, sizeof(local_addr));
    printf("bind(s2) returned error %d\n", WSAGetLastError());

    connect(s1, (sockaddr *)&local_addr, sizeof(local_addr));
    printf("connect(s1) returned error %d\n", WSAGetLastError());

    connect(s2, (sockaddr *)&local_addr, sizeof(local_addr));
    printf("connect(s2) returned error %d\n", WSAGetLastError());

    shutdown(s1, SD_BOTH);
    printf("shutdown(s1) returned error %d\n", WSAGetLastError());

    closesocket(s1);
    printf("closesocket(s1) returned error %d\n", WSAGetLastError());

    connect(s2, (sockaddr *)&local_addr, sizeof(local_addr));
    printf("connect(s2) returned error %d\n", WSAGetLastError());
}

根据我的理解,除了第一次尝试连接s2之外,大多数调用应该返回0,因为s1正在主动使用该连接。但是,不是让我第二次从TIME_WAIT接管,而是返回第二个错误10048.

0 个答案:

没有答案