Get List of IP Routes

Quick method to extract the IP routing table on a PC into a list of lists using a single list comprehension.

Each route table entry is stored in a list where:

[0] = Network Destination
[1] = Netmask
[2] = Gateway
[3] = Interface
[4] = Metric

The active default route will always be the first list in the results [0], so the default next hop for unknown destinations will be [0][3].

from os import popen
from string import split, join
from re import match

rtr_table = [elem.strip().split() for elem in popen("route print").read().split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())]

print "Active default route:", rtr_table[0]

print "Active default next hop:", rtr_table[0][3]

The above comprehension relies on the “Metric” header value. I later realized this may not scale to non-U.S. PCs so here’s a different comprehension that should work for all regions.

[elem.strip().split() for elem in popen("route print").read().split("\n") if match("^[0-9]", elem.strip()) and is_IPv4_Addr(elem.strip().split()[0])]

Important: The above comprehensions don’t take into account that “route print” may be invalid on some PCs…though I’ve never seen this in practice. So you may want to capture the popen output first and check to make sure it’s not blank so the comprehension doesn’t throw an exception.

    return_vals = popen("route print").read()
    if return_vals:
        # U.S. Version
        #rtr_table = [elem.strip().split() for elem in return_vals.split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())]

        # Universal Version ?
        return [elem.strip().split() for elem in return_vals.split("\n") if match("^[0-9]", elem.strip()) and is_IPv4_Addr(elem.strip().split()[0])]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.