Skip to content

Commit

Permalink
pick a random port for tunnel if none are available
Browse files Browse the repository at this point in the history
Change-Id: I65b49019ad67091c554adbaaf1401b5d92e1cb00
  • Loading branch information
vito committed Jan 10, 2012
1 parent 1648e21 commit 7b363fc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
3 changes: 0 additions & 3 deletions lib/cli/commands/services.rb
Expand Up @@ -114,9 +114,6 @@ def tunnel(service=nil, client_name=nil)

err "Unknown service '#{service}'" unless info

# TODO: rather than default to a particular port, we should get
# the defaults based on the service name.. i.e. known services should
# have known local default ports for this side of the tunnel.
port = pick_tunnel_port(@options[:port] || 10000)

raise VMC::Client::AuthError unless client.logged_in?
Expand Down
13 changes: 11 additions & 2 deletions lib/cli/tunnel_helper.rb
Expand Up @@ -210,12 +210,21 @@ def pick_tunnel_port(port)
begin
TCPSocket.open('localhost', port)
port += 1
rescue => e
rescue
return port
end
end

err "Could not pick a port between #{original} and #{original + PORT_RANGE - 1}"
grab_ephemeral_port
end

def grab_ephemeral_port
socket = TCPServer.new('0.0.0.0', 0)
socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
Socket.do_not_reverse_lookup = true
port = socket.addr[1]
socket.close
return port
end

def wait_for_tunnel_start(port)
Expand Down

0 comments on commit 7b363fc

Please sign in to comment.