使用boost :: ASIO是有一个可移植的方式,找出空闲的端口号 [英] Using boost::asio is there a portable way to find out free port number

查看:476
本文介绍了使用boost :: ASIO是有一个可移植的方式,找出空闲的端口号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在试图找出一种方法来找到一个免费的端口号来建立连接,最好用的boost :: ASIO。那么这个端口号将用于监听(只有这样我可以打开一个套接字)。

I'm currently trying to figure out a way to find the number of a free port to establish a connection, ideally with boost::asio. This port number would then be used to listen on (and only then can I open a socket).

粗略地说,有没有办法做到

Roughly, is there a way to do

   tcp::resolver::query query("localhost", port); 

其中端口留空(将其设置为0不工作)

where the port is left blank (setting it to 0 doesn't work)

的看到previously的选项没有一个是便携式的,或有效率。

None of the options seen previously were portable, or efficient.

推荐答案

来处理这只是让操作系统随机选择一个可用的端口,此刻,该插座被绑定到一个端口的最好方法。告诉套接字绑定到端口0,然后查询套接字其绑定到如果成功的实际端口。不要试图找到一个端口的时间提前,然后绑定到它,引入了竞争条件。另一个插座可以捡的端口,你发现后,但在此之前,你可以绑定。

The best way to handle this is to just let the OS pick a random available port at the moment that the socket is being bound to a port. Tell the socket to bind to port 0, then query the socket for the actual port it bound to if successful. Do not try to find a port ahead of time and then bind to it, that introduces a race condition. Another socket could snag the port after you found it but before you could bind it.

这篇关于使用boost :: ASIO是有一个可移植的方式,找出空闲的端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆