如何绑定到任何可用端口?
我需要一个将 UDP 数据包发送到某个网络服务器并接收响应的应用程序。 服务器回复请求所在的相同端口号,因此我首先需要将我的套接字绑定()到任何 UDP 端口号。
对 UDP 端口号进行硬编码是一个坏主意,因为它可能会被同一台 PC 上运行的任何其他应用程序使用。
有没有办法将 UDP 套接字绑定到任何可用端口? IMO 它应该是快速获取空闲端口# 的有效方法,例如accept() 函数使用该端口。
如果不是,那么尝试绑定并检查 WSAEADDRINUSE/EADDRINUSE 状态的最佳策略是什么:从 1025、或 1025+rand() 或其他端口开始按顺序尝试端口?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一种选择是将端口 0 指定给
bind()
。 这将允许您绑定到特定的 IP 地址(如果您安装了多个),同时仍然绑定到随机端口。 如果您需要知道选择了哪个端口,可以在执行绑定后使用getsockname()
。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 usegetsockname()
after the binding has been performed.调用
sendto
,无需首先调用bind
,套接字将自动绑定(到一个空闲端口)。Call
sendto
without callingbind
first, the socket will be bound automatically (to a free port).我肯定漏掉了一些东西,为什么不使用 udp 套接字发回数据呢?
从sendto开始,然后使用recvfrom函数读取传入数据,您还可以获得发送数据的地址作为奖励,就在那里您可以发回响应。
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.