Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a free TCP Port in windows using 'C'

I would like to have two windows applications which communicate over TCP/IP using windows sockets. In this, I want my program to automatically choose the available free port for connection establishment.

Is there a way to find the free TCP port using a C or C++ program?

To be precise, I'd like to automatically detect a free port on the Server side and let the client know the same port(to connect to server).

Thanks for your time!

like image 413
Krish Avatar asked Dec 06 '25 03:12

Krish


1 Answers

I'd like to automatically detect a free port on the Server side

Simply bind() your listening TCP socket to port 0. The OS will pick an available port for you. You can then use getsockname() to retrieve the port that was selected.

let the client know the same port(to connect to server).

You would have to publish the selected TCP listening port somewhere that the client can query it from when needed.

If the client and server are on the same network subnet, one simple solution is to have the server open a separate listening UDP socket on a fixed port, and then have the client send a UDP broadcast to the subnet broadcast IP on that port. When the server receives the broadcast, it can send a reply back to the client specifying the TCP listening port. Then the client can connect to the TCP server on that port.

like image 186
Remy Lebeau Avatar answered Dec 08 '25 01:12

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!