如何绑定到任何可用端口? [英] How to bind to any available port?
问题描述
我需要一个将UDP数据包发送到某些网络服务器并接收响应的应用程序.服务器会回复来自请求的相同端口号,因此我首先需要将套接字绑定()到任何UDP端口号.
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.
对UDP端口号进行硬编码是一个坏主意,因为同一台PC上运行的任何其他应用程序都可能会使用它.
Hardcoding the UDP port number is a bad idea, as it might be used by any other application running on the same PC.
是否可以将UDP套接字绑定到任何可用端口? IMO,这应该是一种快速获得空闲端口号的有效方法,例如, accept()函数.
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.
如果否,那么尝试绑定并检查WSAEADDRINUSE/EADDRINUSE状态的最佳策略是什么:依次尝试从1025或1025 + rand()或其他端口开始的端口?
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?
推荐答案
致电 sendto
而不先调用bind
,套接字将被自动绑定(绑定到空闲端口).
Call sendto
without calling bind
first, the socket will be bound automatically (to a free port).
这篇关于如何绑定到任何可用端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!