Sha256: 4afa8226d8f282baaeb679674e3d27cb60d906a4fb4367944bb6a761219f4bd6

Contents?: true

Size: 1.34 KB

Versions: 19

Compression:

Stored size: 1.34 KB

Contents

require "socket"
require "timeout"

module Vagrant
  module Util
    # Contains the method {#is_ruby_open?} to check if a port is open
    # (listening) or closed (not in use). This method isn't completely
    # fool-proof, but it works enough of the time to be useful.
    module IsPortOpen
      # Checks if a port is open (listening) on a given host and port.
      #
      # @param [String] host Hostname or IP address.
      # @param [Integer] port Port to check.
      # @return [Boolean] `true` if the port is open (listening), `false`
      #   otherwise.
      def is_port_open?(host, port)
        # We wrap this in a timeout because once in awhile the TCPSocket
        # _will_ hang, but this signals that the port is closed.
        Timeout.timeout(1) do
          # Attempt to make a connection
          s = TCPSocket.new(host, port)

          # A connection was made! Properly clean up the socket, not caring
          # at all if any exception is raised, because we already know the
          # result.
          s.close rescue nil

          # The port is open if we reached this point, since we were able
          # to connect.
          return true
        end
      rescue Timeout::Error, Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        # Any of the above exceptions signal that the port is closed.
        return false
      end
    end
  end
end

Version data entries

19 entries across 19 versions & 6 rubygems

Version Path
bmhatfield-vagrant-1.0.10 lib/vagrant/util/is_port_open.rb
bmhatfield-vagrant-1.0.9 lib/vagrant/util/is_port_open.rb
bmhatfield-vagrant-1.0.8 lib/vagrant/util/is_port_open.rb
bmhatfield-vagrant-1.0.7 lib/vagrant/util/is_port_open.rb
vagrantup-1.0.7 lib/vagrant/util/is_port_open.rb
vagrantup-1.0.6 lib/vagrant/util/is_port_open.rb
vagrantup-1.0.5 lib/vagrant/util/is_port_open.rb
vagrantup-1.0.4 lib/vagrant/util/is_port_open.rb
vagrantup-1.0.3 lib/vagrant/util/is_port_open.rb
vagrantup-1.0.2 lib/vagrant/util/is_port_open.rb
vagrant-fixed-ssh-1.0.7 lib/vagrant/util/is_port_open.rb
vagrant-1.0.7 lib/vagrant/util/is_port_open.rb
vagrant-1.0.6 lib/vagrant/util/is_port_open.rb
boxcar-0.10005.1 lib/vagrant/util/is_port_open.rb
fragrant-0.0.5 vendor/bundle/ruby/1.9.1/gems/vagrant-1.0.5/lib/vagrant/util/is_port_open.rb
vagrant-1.0.5 lib/vagrant/util/is_port_open.rb
vagrant-1.0.4 lib/vagrant/util/is_port_open.rb
vagrant-1.0.3 lib/vagrant/util/is_port_open.rb
vagrant-1.0.2 lib/vagrant/util/is_port_open.rb