Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
yegor256 Avatar asked Nov 09 '12 09:11

yegor256


People also ask

How do I find unused TCP ports?

You can use "netstat" to check whether a port is available or not. Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

How do I find out what ports are available?

Open “Terminal”. Type the netstat -a | grep -i “listen” command and press “Enter” to see the list of opened ports.

How do I find my localhost port?

Type portqry.exe -local to launch it. This command displays used TCP and UDP ports for the specified localhost. In addition to all parameters that NetStat displays, Portqry also shows you several port mappings and the number of ports in each state. You can also check for open ports for a remote host.


1 Answers

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

like image 187
yegor256 Avatar answered Oct 23 '22 12:10

yegor256