As to python network programming, we often need to know the external and internal ip of our computer. In this tutorial, we will introduce how to get these two ip using python.
External and internal IP
Our network is separate by routers. Here is an example:
The ip of router, which connects to internet, is the external ip.
The ip of my computer assigned by router is internal ip.
How to get internal ip?
It is easy to get internal ip in python. Here is the example.
import socket from urllib.request import urlopen import urllib
Then we can start to get our internal ip.
def get_private_ip(): print("Getting private IP") ip = socket.gethostbyname(socket.gethostname()) print("IP: " + ip) return ip
We can use socket.gethostbyname() to get our internal ip.
private_ip = get_private_ip() print(private_ip)
Run this code, we can get our internal ip is: 192.168.1.127.
How to get external ip?
It is hard to get external ip by python, because our computer is separated by routers. In order to get the ip of the routers. We can use other api to get.
def get_public_ip(): print("Getting public IP") import re data = str(urlopen('http://checkip.dyndns.com/').read()) # print(data) return re.compile(r'Address: (\d+.\d+.\d+.\d+)').search(data).group(1)
In this function, we can parse data in http://checkip.dyndns.com/ to get our external ip.
public_ip = get_public_ip() print(public_ip)
Run this code, we can get our external ip is: 188.8.131.52