【问题标题】:Unable to bind more than 1021 ports无法绑定超过 1021 个端口
【发布时间】:2016-02-02 17:54:52
【问题描述】:

我正在尝试绑定所有 65535 个 TCP 端口,但实际上只有 1021 个 nmap(以 root 身份运行时)。如果不以 root 身份运行,从 1000 到 60994 的数千个偶尔会出现在 nmap 上。结果反映在 netstat 中。我正在使用完全修补的 Arch Linux。我正在使用非阻塞接受而不是产生 65535 个线程。

nmap -p 1-65535 localhost

还有代码:

#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>  
#include <sys/socket.h>
#include <arpa/inet.h>

void open_tcp(uint16_t port)
{
    static int sockfds[UINT16_MAX] = { 0 };

    struct sockaddr_in serv_addr, cli_addr;
    int cli_len;
    int index = port - 1;

    sockfds[index] = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);

    memset(&serv_addr, 0, sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(port);

    bind(sockfds[index], (struct sockaddr *) &serv_addr, sizeof(serv_addr));
    listen(sockfds[index], 5);

    fcntl(sockfds[index], F_SETFL, fcntl(sockfds[index], F_GETFL, 0) | O_NONBLOCK);

    cli_len = sizeof(cli_addr);

    accept(sockfds[index], (struct sockaddr *) &cli_addr, &cli_len);
}

int main()
{
    uint16_t i;

    for (i = 1; i <= UINT16_MAX; ++i)
    {
        open_tcp(i);
    }

    for (;;) {}

    return 0;
}

这里缺少什么让所有端口正确绑定?

【问题讨论】:

  • 你的代码没有错误检查,那么你怎么可能找出它失败的地方以及为什么?为什么不阻塞地调用一次accept?这几乎可以保证什么都不做。

标签: c++ c linux sockets networking


【解决方案1】:

您可能已经达到了打开文件的最大数量。在调用程序之前尝试增加它:

   ulimit -n 66000

【讨论】:

    猜你喜欢
    • 2015-05-28
    • 2012-06-10
    • 2016-03-08
    • 2017-08-28
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多