Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

关于端口复用问题。tcp客户端已绑定相同端口和地址,断开连接后再发起连接怎么会失败? #638

Open
libaineu2004 opened this issue Nov 1, 2024 · 2 comments

Comments

@libaineu2004
Copy link

libaineu2004 commented Nov 1, 2024

已知TCP服务器的端口和IP是1200, "192.168.1.2"
TCP客户端的端口和IP是1300, "192.168.1.3"
服务器和客户端的运行环境都是Windows 11操作系统。
我希望客户端始终使用相同的端口和IP去连接服务器。但是实际结果却不行,TCP客户端断开连接之后,再发起连接会失败。得过一段时间再连接才成功。也就是说SO_REUSEADDR参数设置没有生效。这是为啥?

源码如下:

void CLight::connect() 
{
    if (m_pClient)
    {
        delete m_pClient;
        m_pClient = nullptr;
    }

    m_pClient = new hv::TcpClient;
    int connfd = m_pClient->createsocket(1200, "192.168.1.2");
    if (connfd < 0)
    {
        return;
    }

    //方法1,不行
    //so_reuseaddr(connfd, 1);

    //方法2,也不行
    int on = 1;
    int off = 0;
    setsockopt(connfd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char *)&off, sizeof(int));
    setsockopt(connfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(int));

    int ret = m_pClient->bind(1300, "192.168.1.3");
    if (ret < 0)
    {
        std::cout << "bind error" << std::endl;
        return;
    }

    m_pClient->onConnection = [=](const hv::SocketChannelPtr &channel) {
        bool connect = channel->isConnected();
    };

   m_pClient->start();
}
@ithewei
Copy link
Owner

ithewei commented Dec 4, 2024

正常来说,设置了SO_REUSEADDR,即使先前的套接字仍处于 TIME_WAIT 状态,新的套接字也可以绑定到相同的地址。

@libaineu2004
Copy link
Author

libaineu2004 commented Dec 4, 2024

正常来说,设置了SO_REUSEADDR,即使先前的套接字仍处于 TIME_WAIT 状态,新的套接字也可以绑定到相同的地址。

我实测了不行呀。大佬能否也写一个测试用例出来,我再试一下。
我是win11系统。
使用
https://www.cmsoft.cn/resource/102.html
的网络调试助手。

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants