سؤال

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?

هل كانت مفيدة؟

المحلول

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()

نصائح أخرى

The 0.0.0.0 in your socket server means you don't configure particular network interface IP address to have your server to listen on. Now it is listening on all server's available IP addresses ( networking interfaces )

To get server IP address (if resolvable by DNS) you can use this:

import socket 
socket.gethostbyname(socket.getfqdn())
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top