Ruby - See if a port is open

后端 未结 7 2088
灰色年华
灰色年华 2020-12-04 14:05

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)
          


        
7条回答
  •  余生分开走
    2020-12-04 15:06

    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
    

提交回复
热议问题