Ruby Programming: Detecting free/used network ports in your Ruby script

Posted by Adrian Fri, 26 Jun 2009 21:03:00 GMT

This snippet shows you how to detect which network ports are in use on the current machine from a Ruby script

When delpoying web applications that run their own web-servers, it is quite likely that the port you want (normally port 80) will be in use. At the very least, it is only good manners to check first.

Here’s a quick Ruby script that will loop through an array of port numbers and return the first one that is free:

require 'socket'

def find_unused_port

  ports = [80, 8000, 8080, 8800, 8088, 8001, 8002, 8003, 8004, 8005, 8006, 8007, 8008]
  port = 0

  ports.each do |p|

    begin

      port = p
      TCPServer.new('localhost', port) rescue port = 0
      if (port > 0) then break; end

    end

  end

  port

end

puts find_unused_port.to_s

It is Ruby because my own applications include a packaged version of the Ruby interpreter. This affords me a great deal of power, being able to execute .rb scripts as part of the install process. You can do similar things in other languages, or, if you don’t mind processing large amounts of text, using the command netstat -a -n, and parsing all that are “LISTENING”.


About

We are a small British company that produces business-oriented software and solutions. These articles are a product of our daily work - information that we think might be useful to share. We hope you find them useful.

Our Software

These are some of our products. Several are open source, some are web-based and others are proprietary:

Categories

Archives

Syndicate

ml> ._trackPageview(); } catch(err) {} ml> l> pageTracker._trackPageview(); } catch(err) {} ml> ._trackPageview(); } catch(err) {} ml> l>