Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C automatically assign port

I just wanted to know how to use C to automatically assign a free port (and see what was used) if a specific port number is not provided.

For example, i'm using this:

struct sockaddr_in address;
address->sin_family = AF_INET;
address->sin_addr.s_addr = INADDR_ANY;
address->sin_port = htons( port );

But how can I replace the sin_port assignment and let C automatically assign for me?

Thanks!

like image 771
Gary Avatar asked Dec 12 '25 07:12

Gary


1 Answers

Matt has already answered the "how to assign a free port" part (use sin_port = 0).

To answer the second part, i.e. "how to see what was used", use getsockname()

like image 66
Jujjuru Avatar answered Dec 14 '25 23:12

Jujjuru



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!