Python Get Network External and Internal IP: A Step Guide – Python Tutorial

By | September 2, 2020

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:

External and internal IP of the network

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 libraries

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.

For example:

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: 117.152.5.124

Leave a Reply

Your email address will not be published. Required fields are marked *