Hi I want to get the default network interface using Python.
After google, I got pynetinfo can do this. But pynetinfo seems not work on Python3.
Is there another method to instead pynetinfo?
If you are using Linux you can examining the route table directly on /proc/net/route. This file contains the routing parameters of your system, here is an example:
Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
eth1 0009C80A 00000000 0001 0 0 0 00FFFFFF 0 0 0
eth2 0000790A 00000000 0001 0 0 0 0080FFFF 0 0 0
eth3 00007A0A 00000000 0001 0 0 0 0080FFFF 0 0 0
eth0 00000000 FE09C80A 0003 0 0 0 00000000 0 0 0
In this example all traffic to networks 10.200.9.0/24, 10.121.0.0/25 and 10.122.0.0/25 is broadcasted via eth1, eth2 and eth3 respectively, the rest of packages are sent using eth0 interface to the gateway 10.200.9.254. So the question is how to get this programatically using Python?
def get_default_iface_name_linux():
route = "/proc/net/route"
with open(route) as f:
for line in f.readlines():
try:
iface, dest, _, flags, _, _, _, _, _, _, _, = line.strip().split()
if dest != '00000000' or not int(flags, 16) & 2:
continue
return iface
except:
continue
get_default_iface_name_linux() # will return eth0 in our example
with pyroute2:
from pyroute2 import IPDB
ip = IPDB()
# interface index:
print(ip.routes['default']['oif'])
# interface details:
print(ip.interfaces[ip.routes['default']['oif']])
# release DB
ip.release()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With