Created
July 2, 2011 12:15
-
-
Save ssokolow/1059982 to your computer and use it in GitHub Desktop.
Snippet for getting the default gateway on Linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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() |
Author
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
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
<instruct.pack('<L', ...with=so the code will use the machine's native endianness.