Skip to content

Instantly share code, notes, and snippets.

@ptisserand
Last active May 5, 2021 08:57
Show Gist options
  • Save ptisserand/e114e6f1887366fd25cd53a5fd9646a9 to your computer and use it in GitHub Desktop.
Save ptisserand/e114e6f1887366fd25cd53a5fd9646a9 to your computer and use it in GitHub Desktop.
Python code to retrieve gateway IP
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