Ruby - See if a port is open

后端 未结 7 2051
灰色年华
灰色年华 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 14:43

    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:

    • https://spin.atomicobject.com/2013/09/30/socket-connection-timeout-ruby/

提交回复
热议问题