Finding an unused network port for server applications with Ruby 1

Posted by Adrian O'Connor Thu, 04 Oct 2007 09:05:00 GMT

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”.

Comments

Leave a response

  1. ricpersi about 1 month later:

    thanks,

    found this code snippet really helpful!
Comments