Skip to content

Instantly share code, notes, and snippets.

@ssokolow
Created July 2, 2011 12:15
Show Gist options
  • Select an option

  • Save ssokolow/1059982 to your computer and use it in GitHub Desktop.

Select an option

Save ssokolow/1059982 to your computer and use it in GitHub Desktop.
Snippet for getting the default gateway on Linux
#Snippet for getting the default gateway on Linux
#No dependencies beyond Python stdlib
import socket, struct
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
if __name__ == '__main__':
print get_default_gateway_linux()
@ssokolow
Copy link
Author

ssokolow commented Jul 2, 2011

I don't have a big-endian machine to test on, so I'm not sure whether the endianness is dependent on your processor architecture, but if it is, replace the < in struct.pack('<L', ... with = so the code will use the machine's native endianness.

@NickPryorMe
Copy link

NickPryorMe commented Aug 14, 2017

Thanks, I like your solution. It works with Python3, just change the print statement to a print function instead.

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