user1639431 user1639431 - 1 year ago 198
HTTP Question

Is it possible to run python SimpleHTTPServer on localhost only?

I have a vpn connection and when I'm running python -m SimpleHTTPServer, it serves on, which means it can be accessed via localhost and via my real ip.
I don't want robots to scan me and interested that the server will be accessed only via localhost.

Is it possible?

python -m SimpleHTTPServer # doesn't work.

Any other simple http server which can be executed instantly using the command line is also welcome.

Answer Source

If you read the source you will see that only the port can be overridden on the command line. If you want to change the host it is served on, you will need to implement the test() method of the SimpleHTTPServer and BaseHTTPServer yourself. But that should be really easy.

Here is how you can do it, pretty easily:

import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

def test(HandlerClass=SimpleHTTPRequestHandler,

    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)
                port = int(sys.argv[1])
                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], "..."

if __name__ == "__main__":

And to use it:

> python     
Serving HTTP on port 8000 ...

> python
Serving HTTP on port 9000 ...

> python 8080          
Serving HTTP on port 8080 ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download