48

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

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:

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?

Edit: 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.

8 Answers 8

55

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
5
  • I had some trouble with this blocking (I think). Basically the timeout wouldn't actually time out. Not sure why, but the netcat solution worked well in its place. Oct 27, 2011 at 16:26
  • 2
    This answer has a solution that also works on windows: stackoverflow.com/a/3473208/362951
    – mit
    Jul 8, 2012 at 20:22
  • 2
    Shouldn't true/false be swapped?
    – Leopd
    Oct 29, 2012 at 4:09
  • Add in there some command line options, and you've got a functional program!
    – FilBot3
    Dec 19, 2014 at 20:05
  • Please watch out with this code. Timeout::timeout is really bad, as much as it can "work" in smaller scripts, it will introduce hard to track errors in bigger applications. Some reading: jvns.ca/blog/2015/11/27/… Oct 4, 2019 at 20:55
30

All other existing answer are undesirable. Using Timeout is discouraged. Perhaps things depend on ruby version. At least since 2.0 one can simply use:

Socket.tcp("www.ruby-lang.org", 10567, connect_timeout: 5) {}

For older ruby the best method I could find is using non-blocking mode and then select. Described here:

1
  • 7
    Worked perfectly for me: port_is_open = Socket.tcp(host, port, connect_timeout: 5) { true } rescue false. It's easy to expand from a one-liner to rescue the specific exceptions needed.
    – anothermh
    Oct 1, 2016 at 18:01
27

More Ruby idiomatic syntax:

require 'socket'
require 'timeout'

def port_open?(ip, port, seconds=1)
  Timeout::timeout(seconds) do
    begin
      TCPSocket.new(ip, port).close
      true
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
      false
    end
  end
rescue Timeout::Error
  false
end
4
  • This gave a false positive for the inputs '192.0.2.0', 80, 10 which should be invalid (according to stackoverflow.com/questions/10456044/…). I got the same result with Ruby 1.9.3p448 and 2.0.0p195, both on Mac. In what situations does this method manage to return false? (I even tried writing to the socket before closing it, but that still returned true!)
    – glyn
    Sep 6, 2013 at 10:56
  • I think this function def is missing a begin statement before timeout, or is that somehow optional? (rescue Timeout::Error should be in a begin block, shouldn't it?)
    – nash
    Jun 12, 2014 at 13:02
  • @nash Ruby permits a rescue clause to belong to the method itself. In effect, the method is an implicit block. Jun 27, 2014 at 23:57
  • 1
    wouldn't it be be even better to enclose the Timeout block in the inner begin...rescue one, and analyze the errors at the same indentation level!
    – caesarsol
    Dec 16, 2014 at 15:03
16

I recently came up with this solution, making use of the unix lsof command:

def port_open?(port)
  !system("lsof -i:#{port}", out: '/dev/null')
end
4
  • 2
    This was very nice for me. I wanted to introduce a system of assigning ports to virtual machines in vagrant and wrote this one-liner to check to see if the port I was about to assign was open or not: vms['port'] += 1 while ports.include? vms['port'] or system("lsof -i:#{vms['port']}")
    – Dannid
    Nov 2, 2014 at 18:32
  • 1
    This only works for the logged in user. To work across the board, use sudo lsof -i:<port>
    – alpinweis
    Jun 30, 2016 at 2:07
  • I had to remove the ! (not operator) to get this to work. Jan 13, 2017 at 19:21
  • "open" here means "in use" so this will return false when the port is "free"
    – grosser
    Apr 19, 2018 at 15:58
9

Just for completeness, the Bash would be something like this:

$ netcat $HOST $PORT -w 1 -q 0 </dev/null && do_something

-w 1 specifies a timeout of 1 second, and -q 0 says that, when connected, close the connection as soon as stdin gives EOF (which /dev/null will do straight away).

Bash also has its own built-in TCP/UDP services, but they are a compile-time option and I don't have a Bash compiled with them :P

3
  • 1
    They're pretty simple: just pretend /dev/{tcp}/HOST/PORT are files :)
    – ephemient
    Feb 6, 2009 at 20:38
  • 2
    For future reference, I found this as nc on my system rather than netcat
    – HXCaine
    Aug 6, 2013 at 10:34
  • 1
    Warning: On MacOS X, this gives the error nc: invalid option -- q. The following works on both MacOS X and Ubuntu, and seems simpler to me: nc -z $HOST $PORT
    – mercurial
    Oct 7, 2016 at 16:09
1

My slight variation to Chris Rice's answer. Still handles timing out on a single attempt but also allows multiple retries until you give up.

    def is_port_open?(host, port, timeout, sleep_period)
      begin
        Timeout::timeout(timeout) do
          begin
            s = TCPSocket.new(host, port)
            s.close
            return true
          rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
            sleep(sleep_period)
            retry
          end
        end
      rescue Timeout::Error
        return false
      end
    end
1

All *nix platforms:

try nc / netcat command as follow.

`nc -z -w #{timeout_in_seconds} -G #{timeout_in_seconds} #{host} #{port}`
if $?.exitstatus == 0
  #port is open
else
  #refused, port is closed
end

The -z flag can be used to tell nc to report open ports, rather than initiate a connection.

The -w flag means Timeout for connects and final net reads

The -G flag is connection timeout in seconds

Use -n flag to work with IP address rather than hostname.

Examples:

# `nc -z -w 1 -G 1 google.com 80`
# `nc -z -w 1 -G 1 -n 123.234.1.18 80`
1

My solution is derived from the posted solutions.

require 'socket'
def is_port_open?(ip, port)
  begin
    s = Socket.tcp(ip, port, connect_timeout: 5)
    s.close
    return true
  rescue => e
    # possible exceptions:
    # - Errno::ECONNREFUSED
    # - Errno::EHOSTUNREACH
    # - Errno::ETIMEDOUT
    puts "#{e.class}: #{e.message}"
    return false
  end
end
1
  • This is a better answer, thanks!
    – jrochkind
    Dec 7, 2021 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.