Skip to content

Instantly share code, notes, and snippets.

@mzpqnxow
Last active September 12, 2021 00:33
Show Gist options
  • Save mzpqnxow/9ed50b50f447b1f4f7baaf9b17b07e55 to your computer and use it in GitHub Desktop.
Save mzpqnxow/9ed50b50f447b1f4f7baaf9b17b07e55 to your computer and use it in GitHub Desktop.
Get default route on Linux in Python, without imports (sorry)
def default_route(verbose=False):
"""Get default route on Linux
ATTENTION: There is a much simpler way to do this, using a dummy UDP "connection"
and getpeername. Use that instead, it's much more portable.
Hacky way to get the route from an interface, i.e. 'eth0' => '192.168.1.1'
On machines that have a default route on another interface, this function
should be used
This configuration is especially common on testing machines where the router
may be on a test LAN, with the default route being a different router than
the one being targeted
"""
if 'linux' not in platform.lower() != 'linux':
raise RuntimeError('interface_to_router only supports Linux OS')
gateway_ip = None
default_route_field_name = 'destination'
gateway_field_name = 'gateway'
if verbose is True:
print('[verbose] determining machine default route')
route_file = open('/proc/net/route', 'rb')
headers = route_file.readline().strip().split()
for index, header in enumerate(headers):
headers[index] = header.lower()
for route_fields in [row.strip().split() for row in route_file.readlines()]:
labeled_route_row = dict(zip(headers, route_fields))
destination_name = labeled_route_row.get(default_route_field_name, None)
default_route_decimal = int(destination_name, 0x10)
if default_route_decimal == 0:
gateway = labeled_route_row.get(gateway_field_name, None)
gateway_decimal = htonl(int(gateway, 0x10))
gateway_ip = inet_ntoa(pack('!I', gateway_decimal))
if verbose is True:
print('[verbose] found default route {}'.format(gateway_ip))
break
return gateway_ip
@mzpqnxow
Copy link
Author

Can't guarantee this will work forever ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment