Skip to content

Instantly share code, notes, and snippets.

@jplazcano87
Created August 24, 2016 18:06
Show Gist options
  • Save jplazcano87/c65f759616d7da91f878d6bc8400d644 to your computer and use it in GitHub Desktop.
Save jplazcano87/c65f759616d7da91f878d6bc8400d644 to your computer and use it in GitHub Desktop.
SimpleHttpServer with ip and port
import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
def test(HandlerClass=SimpleHTTPRequestHandler,
ServerClass=BaseHTTPServer.HTTPServer):
protocol = "HTTP/1.0"
host = ''
port = 8000
if len(sys.argv) > 1:
arg = sys.argv[1]
if ':' in arg:
host, port = arg.split(':')
port = int(port)
else:
try:
port = int(sys.argv[1])
except:
host = sys.argv[1]
server_address = (host, port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == "__main__":
test()
> python server.py 127.0.0.1
Serving HTTP on 127.0.0.1 port 8000 ...
> python server.py 127.0.0.1:9000
Serving HTTP on 127.0.0.1 port 9000 ...
> python server.py 8080
Serving HTTP on 0.0.0.0 port 8080 ...
@loretoparisi
Copy link

When htting Ctrl-C, this will not shutdown the server gracefully, and the binded address will be in use then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment