Today most computers are connected to routers and behind firewalls, leaving them with a different internal and external IP address. Browsing the web for how to find these addresses returns many over-complicated solutions as well as a bunch that just don’t do what they claim. So here’s a simple one.
The internal IP address is known since this is what the router assigned to your computer:
import socket internal_ip = socket.gethostbyname(socket.gethostname())
It’s different with the external IP address however. Your computer can’t tell from the router connected to the outside world what IP address it possesses. The reason for this is that the router can be located several steps away in the network chain. So in order to retrieve the external IP address we’ll have to connect to a computer outside our intranet and get it to tell us the IP address it sees. Luckily there are some services out there who does just that. whatismyip.org generates a string with the IP it sees when your computer connects, so we just read it back:
import urllib external_ip = urllib.urlopen('http://whatismyip.org').read()
Note that any error handling is left out that this is for IPv4 only. IPv6 may require a different approach.