Why can't I access my SockectServer on my local network while I can access my computer?
I am creating a socket server with python module SocketServer
:
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
I can access the server http://localhost:9999/
on my computer, but I can not access with your phone (my phone is in the local network, because I connect Wi-Fi with your computer.) With the IP: http://192.168.123.1:9999
.
I used python -m SimpleHTTPServer 9999
to test my network, I can access my computer using my phone.
source to share
When you speak localhost
as the hostname of the server, the HTTP server will only select requests that target localhost
or 127.0.0.1
. When accessing it from your mobile phone, you will likely be accessing it with the computer's actual IP address, which will not be 127.0.0.1
or localhost
. This is why the server does not collect these requests.
To indicate that you want to respond to all requests given on this computer, regardless of the IP address or hostname used to access the server, you must use 0.0.0.0
bothHOST
HOST, PORT = "0.0.0.0", 9999
source to share