Skip to content

Instantly share code, notes, and snippets.

@jccovey
Forked from schmidt/web
Created June 16, 2010 03:20
Show Gist options
  • Save jccovey/440112 to your computer and use it in GitHub Desktop.
Save jccovey/440112 to your computer and use it in GitHub Desktop.
Serve current directory on next available port
#!/usr/bin/env ruby
require 'webrick'
require 'socket'
require 'timeout'
# code from http://stackoverflow.com/questions/517219/ruby-see-if-a-port-is-open/517638#517638
def port_in_use?(port)
begin
Timeout::timeout(1) do
begin
s = TCPSocket.new('0.0.0.0', port)
s.close
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
end
rescue Timeout::Error
end
return false
end
def port_above(port)
while port_in_use?(port)
port += 1
end
port
end
s = WEBrick::HTTPServer.new(:Port => port_above(3000),
:DocumentRoot => Dir::pwd)
trap("INT") { s.shutdown }
s.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment