Ziggy
Ziggy

Reputation: 95

Unable to bind more than 1021 ports

I am trying to bind all 65535 TCP ports, however only 1021 actually nmap (when run as root). If not run as root, several thousand from 1000-60994 sporadically show up on nmap. The results are mirrored in netstat. I am using fully patched Arch Linux. I am using a nonblocking accept instead of spawning 65535 threads.

nmap -p 1-65535 localhost

And the code:

#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;
}

What is missing here to get all ports to bind correctly?

Upvotes: 1

Views: 93

Answers (1)

epx
epx

Reputation: 1096

You probably bumped the maximum number of open files. Try to increse it before calling the program:

   ulimit -n 66000

Upvotes: 3

Related Questions