-
-
Save schmidt/16537 to your computer and use it in GitHub Desktop.
Instant webserver for current dir. Fetches free port automatically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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