Summary: In this programming tutorial, we will learn to check our machine’s external IP address using Python.
What is an External IP Address?
The external IP address is the address assigned to our machine by our ISP (Internet Service Provider) which the internet (all the machines outside of our local network) use to identify us.
How to Find the External IP Address?
If we try to find the IP address using a program that runs on our local machine, we will get the local address instead of the external address.
So we need to use the external source to get the external IP address assigned to our machine by ISP.
Method 1: Using Third Party
from requests import get
ip = get('https://ipapi.co/ip/').text # or get('https://api.ipify.org').text
print(ip)
In this method, we fetch the IP address of our machine using a third-party website.
For this, we make a GET request on the given address using the get()
method of the requests library.
Note: This example requires the requests library to be installed. So make sure you install it before importing it into your python program.
Tip: If you are connected to VPN then use the Amazon AWS endpoint ‘https://checkip.amazonaws.com’ to get your external IP address.
Method 2: Using UPnP Protocol
We can also use the UPnP protocol to query the external IP address of our router. Most importantly, this does not rely on an external service.
To use this, we use an external library called miniupnpc.
Use the following pip statement in the console to install the miniupnpc library in our python environment:
pip install miniupnpc
After installation, we use the library as follows to fetch the external IP address in Python:
import miniupnpc
u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))
This method is not reliable when the machine is connected to some VPN.
It is recommended to use the external service (as specified in method 1) to get the proper result.
I hope everything is clear to you all. If you have any doubts or suggestions then please comment below.