Search code examples
bashnetwork-programmingtcpport

How to get the first available TCP port to listen to?


I want to attach my service to some TCP port, for testing purposes. Then, I will make calls to this port, make sure the service works, and shut it down. I need to find a way how to generate such a port number, since I can't use a fixed one - tests may run in parallel. Is it possible?


Solution

  • This is how I do it:

    #include <stdio.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    
    int main() {
        struct sockaddr_in addr;
        socklen_t len = sizeof(addr);
        addr.sin_port = 0;
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0) {
            perror("socket()");
            return -1;
        }
        if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) != 0) {
            perror("bind()");
            return -1;
        }
        if (getsockname(sock, (struct sockaddr*) &addr, &len) != 0) {
            perror("getsockname()");
            return -1;
        }
        printf("%d\n", addr.sin_port);
        return 0;
    }
    

    Then, compile it and run:

    cc -o reserve reserve.c && ./reserve
    

    And it outputs the port number, available for binding.

    I published a full version of the tool in Github: https://github.com/yegor256/random-tcp-port