开发者

C automatically assign port

开发者 https://www.devze.com 2022-12-31 07:41 出处:网络
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.

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 auto开发者_开发问答matically assign for me?

Thanks!


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()


Just use a value of 0.

address->sin_port = 0

Alternatively, you can completely skip the binding step if you don't care which interface you use, either.

0

精彩评论

暂无评论...
验证码 换一张
取 消