How to bind to any available port?

2019-01-13 02:58发布

I need an app that sends an UDP packet to some network server and receives the response. The server replies to the same port number where request came from, so I first need to bind() my socket to any UDP port number.

Hardcoding the UDP port number is a bad idea, as it might be used by any other application running on the same PC.

Is there a way to bind an UDP socket to any port available? IMO it should be an effective way to quickly obtain a free port #, which is used by e.g. accept() function.

If no, then what's the best strategy to try binding and check for WSAEADDRINUSE/EADDRINUSE status: try the ports sequentially starting from from 1025, or 1025+rand(), or some other?

3条回答
Fickle 薄情
2楼-- · 2019-01-13 03:42

Another option is to specify port 0 to bind(). That will allow you to bind to a specific IP address (in case you have multiple installed) while still binding to a random port. If you need to know which port was picked, you can use getsockname() after the binding has been performed.

查看更多
贼婆χ
3楼-- · 2019-01-13 03:43

I must be missing something, why don't you use the udp socket to send back data? Start with sendto and then use recvfrom function to read incoming data also you get as a bonus the address from which the data was sent, right there for you to send a response back.

查看更多
你好瞎i
4楼-- · 2019-01-13 03:44

Call sendto without calling bind first, the socket will be bound automatically (to a free port).

查看更多
登录 后发表回答