Broomerr
Broomerr

Reputation: 59

Ruby: check if local port is listening

I want to implement check in ruby if local port is listening or is free. Needed that script return code in case of free port is 0 and in case of port occupied (listening) return code is 1.

Important here is that port is local and not remote! For remote port I have found this solution: Ruby - See if a port is open

I have tried this script:

ruby -e " 
    require 'socket' ; 
    server=TCPServer.new(25) ; 
    if server==nil ; 
        return 1 ; 
    else server.close ; 
    end 
"

It returns "0" in case of free port, but in case when port occupied it return

-e:1:in `initialize': no implicit conversion of nil into String (TypeError)
        from -e:1:in `new'
        from -e:1:in `<main>'

So how to correct that line script?

Upvotes: 1

Views: 1337

Answers (1)

Inpego
Inpego

Reputation: 2667

Try:

ruby -e "require 'socket';
begin
  sock = Socket.new(Socket::Constants::AF_INET, Socket::Constants::SOCK_STREAM, 0);
  sock.bind(Socket.pack_sockaddr_in(YOUR_PORT_HERE, '0.0.0.0'));
  exit(0);
rescue Errno::EADDRINUSE;
  exit(1);
end"

(replace YOUR_PORT_HERE by actual port number and remove newlines if you want)

Upvotes: 3

Related Questions