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?
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.
Open “Terminal”. Type the netstat -a | grep -i “listen” command and press “Enter” to see the list of opened ports.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With