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(('google.com', 80))
return s.getsockname()[0]
Another great snippet for finding the IP address of a given network interface is in the ASPN Python Cookbook.

3 comments:

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

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

    ReplyDelete