Sometimes, we may need to know the default gateway ip of our computer. In this tutorial, we will introduce how to get this ip by python netifaces library.
Install python netifaces library
We can use pip install command to install.
pip install netifaces
If you get Microsoft Visual C++ 14.0 is required error, you can read this tutorial to fix.
Best Practice to Fix Python Pip Microsoft Visual C++ 14.0 is required Error – Python Tutorial
Import library
import netifaces
Gate gateway information
We can use netifaces.gateways() to get the gateway information.
# gets gateway of the network gws = netifaces.gateways() print(gws)
gws is:
{2: [('192.168.1.1', '{0D61DA8C-6081-4A86-9CAB-E53126A2404D}', True)], 'default': {2: ('192.168.1.1', '{0D61DA8C-6081-4A86-9CAB-E53126A2404D}')}}
Then we can get the default gateway ip.
Get the default getway ip
gateway = gws['default'][netifaces.AF_INET][0] print(gateway)
Run this code, we will get ip:
192.168.1.1