Ruby - 查看端口是否打开 [英] Ruby - See if a port is open
问题描述
我需要一种快速的方法来确定给定端口是否已使用 Ruby 打开.我目前正在摆弄这个:
I need a quick way to find out if a given port is open with Ruby. I currently am fiddling around with this:
require 'socket'
def is_port_open?(ip, port)
begin
TCPSocket.new(ip, port)
rescue Errno::ECONNREFUSED
return false
end
return true
end
如果端口是开放的,它工作得很好,但它的缺点是偶尔它会坐下来等待 10-20 秒,然后最终超时,抛出 ETIMEOUT
异常(如果端口关闭).我的问题是:
It works great if the port is open, but the downside of this is that occasionally it will just sit and wait for 10-20 seconds and then eventually time out, throwing a ETIMEOUT
exception (if the port is closed). My question is thus:
是否可以将此代码修改为仅等待一秒钟(如果到那时我们什么也得不到,则返回 false
)或者是否有更好的方法来检查给定端口是否在给定端口上打开主持人?
Can this code be amended to only wait for a second (and return false
if we get nothing back by then) or is there a better way to check if a given port is open on a given host?
调用 bash 代码也是可以接受的,只要它可以跨平台工作(例如,Mac OS X、*nix 和 Cygwin),尽管我更喜欢 Ruby 代码.
Calling bash code is acceptable also as long as it works cross-platform (e.g., Mac OS X, *nix, and Cygwin), although I do prefer Ruby code.
推荐答案
类似下面的方法可能会起作用:
Something like the following might work:
require 'socket'
require 'timeout'
def is_port_open?(ip, port)
begin
Timeout::timeout(1) do
begin
s = TCPSocket.new(ip, port)
s.close
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
end
rescue Timeout::Error
end
return false
end
这篇关于Ruby - 查看端口是否打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!