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
In Rails - Is There a Rails Method to Convert Newlines to <Br>
Strange Inability to Require Config/Boot After Upgrading to Ruby 1.9.2
Ruby 1.9 Hash with a Dash in a Key
How to Make Part of a Regular Expression Optional in Ruby
What Is an Illegal Octal Digit
How to Invoke an Instance Method on a Ruby Module Without Including It
Devise Logged in Root Route Rails 3
Convert a .Doc or .Pdf to an Image and Display a Thumbnail in Ruby
How to Get the Current Time as 13-Digit Integer in Ruby
Redefining a Single Ruby Method on a Single Instance with a Lambda
Colon (:) Appears as Forward Slash (/) When Creating File Name
Set Attribute Dynamically of Ruby Object
Rails on Windows - Install Issue
Google Maps, Ruby on Rails, Zoom Level with One Marker