gpt4 book ai didi

ruby - 你如何在 Ruby 中找到一个随机开放的端口?

转载 作者:数据小太阳 更新时间:2023-10-29 07:20:45 24 4
gpt4 key购买 nike

如果您调用 DRb.start_service(nil, some_obj) 然后调用 DRb.uri,您会得到本地 URI,包括端口号,另一个进程可以用于调用电话。

我只想让一些代码找到一个随机可用端口并返回该端口号,而不是启动一个完整的 DRb 服务。有没有在 Ruby 中执行此操作的简单方法?

最佳答案

还没有尝试过,但这可能有效。

来自 http://wiki.tcl.tk/2230

The process can let the system automatically assign a port. For
both the Internet domain and the XNS domain, specifying a port number of 0 before calling bind() requests the system to do this.

另见 http://www.ruby-doc.org/stdlib/libdoc/socket/rdoc/classes/Socket.html#M003723

 require 'socket'

# use Addrinfo
socket = Socket.new(:INET, :STREAM, 0)
socket.bind(Addrinfo.tcp("127.0.0.1", 0))
p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP>

注意在 socket.bind 调用中使用端口 0。预期行为是 local_address 将包含随机开放端口。

关于ruby - 你如何在 Ruby 中找到一个随机开放的端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5985822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com