Last active
May 5, 2021 08:57
-
-
Save ptisserand/e114e6f1887366fd25cd53a5fd9646a9 to your computer and use it in GitHub Desktop.
Python code to retrieve gateway IP
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
def get_default_gateway(): | |
try: | |
hip = None | |
with open("/proc/self/net/route") as routes: | |
for line in routes: | |
parts = line.split('\t') | |
if '00000000' == parts[1]: | |
hip = parts[2] | |
if hip is not None and len(hip) == 8: | |
# Reverse order, convert hex to int | |
return "%i.%i.%i.%i" % (int(hip[6:8], 16), int(hip[4:6], 16), int(hip[2:4], 16), int(hip[0:2], 16)) | |
except Exception: | |
logger.warning("get_default_gateway: ", exc_info=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment