DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Find Next Highest Available Port

10.09.2008
| 1362 views |
  • submit to reddit
        This function loops until the next available port on the local machine is found. This code is not for remote port scanning--it works on your own machine if you need to dynamically find a non-used port, perhaps because you're running large numbers of servers locally or some other edge case.

  def next_available_port(port)
    port_found=false
    until(port_found==true )
      begin
       TCPServer.new(port).close
       port_found=true
      rescue Exception=>e
        puts "PORT exception #{e.message}"
        port+=1
      end
    end
    port
  end