红宝石 - 请参阅如果一个端口是开放的 [英] 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:
可以这样code修改为只等待一秒钟(并返回假
,如果我们什么都不拿回来的话),或者是有更好的方法来检查如果给定的端口给定主机上打开?
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 code是可以接受的,只要它的工作原理跨平台(如Mac OS X中,* nix中,和Cygwin),虽然我做的preFER红宝石code。
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
这篇关于红宝石 - 请参阅如果一个端口是开放的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!