Ruby - See If a Port Is Open

Ruby - See if a port is open

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 One liner | test remote host port

The main difference is that Ruby will raise an error if it cannot establish the IO, so you need to rescue the error condition. It changes the flow somewhat, but is still very do-able:

loop { break if (TCPSocket.open("localhost",80) rescue nil); puts "Wait...."; sleep 1 }

As seen from other answer, it is possible to make a more literal conversion from the Perl version. Just use the Ruby expression (TCPSocket.open("localhost",80) rescue nil) to replace Perl's new IO::Socket::INET("localhost:80") so that Ruby's raise an error behaviour better matches Perl's return undef when cannot create the object.

Suppress nil response from Ruby method

Whether you only need to check for a condition (port is open):

require 'timeout'
require 'socket'

def is_port_open? host, port
@host = host || "localhost"
@port = port || "8080"
begin
Timeout::timeout(1) do
begin
s = TCPSocket.new(@host, @port)
s.close
return true # success
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false # socket error
end
end
rescue Timeout::Error
end
return false # timeout error
end

is_port_open? 'localhost', 8080
#⇒ true
is_port_open? 'localhost', 11111
#⇒ false

It’s now up to you what to return in case of error etc. Please note, that another option would be to let exceptions propagate to caller. This function would be a way shorter, but you’ll need to handle exceptions in caller.



Related Topics



Leave a reply



Submit