title: Ruby - See if a port is open
body: <p>I need a quick way to find out if a given port is open with Ruby. I currently am fiddling around with this:</p>
  
  <pre><code>require 'socket'
  
  def is_port_open?(ip, port)
    begin
      TCPSocket.new(ip, port)
    rescue Errno::ECONNREFUSED
      return false
    end
    return true
  end
  </code></pre>
  
  <p>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 <code>ETIMEOUT</code> exception (if the port is closed). My question is thus:</p>
  
  <p>Can this code be amended to only wait for a second (and return <code>false</code> 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?</p>
  
  <p><strong>Edit:</strong> 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.</p>