Thursday, 30 May 2013

Ruby - Check if a port is open

This requires the socket class so the following needs to be included at the top of the program:-
 require 'socket'  
The code here below can be used to see if linux is listening on a particular port.
 def port_open?(ip, port, timeout)  
  start_time = Time.now  
  current_time = start_time  
  while (current_time - start_time) <= timeout  
   begin  
    TCPSocket.new(ip, port)  
    return true  
   rescue Errno::ECONNREFUSED  
    sleep 0.1  
   end  
   current_time = Time.now  
  end  
  return false  
 end  
This can be called with the following:-
 port_open?(Socket.gethostname, 80, 10)