Search code examples
pythonsocketserver

Python SocketServer - Get own IP


I'm creating a simple TCP server with Python3's socketserver module. I want to get the IP of the server that the server is serving on.

I noticed that there is a server_address attribute in socketserver (rather, BaseServer), but that returns '0.0.0.0' for the IP. I've also tried using the socket object and running gethostbyname(), but python says that the socket object does not have attribute gethostbyname. Example:

server = socketserver.TCPServer(...)
print(server.server_address) # gives me ('0.0.0.0', [correct port])
print(server.socket.gethostbyname()) # AttributeError

From what I understand, 0.0.0.0 is reserved for "unknown", so the server isn't seeing its IP. Is that correct? What might the solution be?


Solution

  • This isn't possible without help from an external server, because there could be any number of network address translators (NATs) between you and another computer. I suppose that if you were working with some kind of custom protocol you could ask a client to assert the address to which it is connected.

    With this in mind (many would consider this a hack), but it is arguably the only way- you could do something like:

    import urllib.request
    external_ip = urllib.request.urlopen('http://ifconfig.me/ip').read()