If you work with IPv6 or with servers with multiple network interfaces, this command will not work correctly.
Instead, you can use this command, which tries to connect to the Google DNS server on 8.8.8.8 on port 53 and return your ip:
import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])
source
share