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].

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.

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.

Leave a Reply

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