Finding your public IP address in Python

I came across a nice code snippet today to accomplish this. Naturally, this doesn't work for NAT.
def GetPublicIpAddress():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('', 80))
return s.getsockname()[0]
Another great snippet for finding the IP address of a given network interface is in the ASPN Python Cookbook.


  1. Thanks For Your information about the ip address.I know the my internet ip address from the site yours I learned about the how to find the public ip address.Thank U.

  2. I think, the easiest way is to just read from, which gives you your outer ip in plaintext.