Over a million developers have joined DZone.

Find Next Highest Available Port

·
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
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}