Using Python socket to get public address

import socket

port = 80
host = "www.google.com"
print("Creating socket...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected from", s.getsockname())
print("Connected to", s.getpeername())

可以使用getsocketname()返回本地ip地址与端口号,getpeername()返回服务器ip地址与端口号。

or use UDP to connect

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()

or running in shell

alias myip="python3 -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(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]]) if l][0][0])'"

myip