Search code examples
pythonhttpserverbasehttpserver

Why host http server needs to specify the IP on which it is hosting?


I am hosting a http server on Python using BaseHTTPServer module.

I want to understand why it's required to specify the IP on which you are hosting the http server, like 127.0.0.1/192.168.0.1 or whatever. [might be a general http server concept, and not specific to Python]

Why can't it be like anybody who knows the IP of the machine could connect to the http server?

I face problems in case when my http server is connected to two networks at the same time, and I want to serve the http server on both the networks. And often my IP changes on-the-fly when I switch from hotspot mode on the http server machine, to connecting to another wifi router.


Solution

  • You must specify the IP address of the server, mainly because the underlying system calls for listening on a socket requires it. At a lower level you declare what pair (IP address, port) you want to use, listen on it and accept incoming connexions.

    Another reason is that professional grade server often have multiple network interfaces and multiple IP addresses, and some services only need to listen on some interface addresses.

    Hopefully, there are special addresses:

    • localhost or 127.0.0.1 is the loopback address, only accessible from local machine. It is currently used for tests of local services
    • 0.0.0.0 (any) is a special address used to declare that you want to listen to all the local interfaces. I think that it is what you want here.