Python Get Default Gateway IP Using Netifaces: A Step Guide – Python Tutorial

By | September 1, 2020

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

python pip install netifaces

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()

gws is:

{2: [('', '{0D61DA8C-6081-4A86-9CAB-E53126A2404D}', True)], 'default': {2: ('', '{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]

Run this code, we will get ip:

Leave a Reply

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