Skip to content

Instantly share code, notes, and snippets.

@schmidt
Created October 13, 2008 13:37
Show Gist options
  • Save schmidt/16537 to your computer and use it in GitHub Desktop.
Save schmidt/16537 to your computer and use it in GitHub Desktop.
Instant webserver for current dir. Fetches free port automatically.
#!/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