DeaD_EyE

obtain ip address and gateways

May 30th, 2020
2,898
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. Example to obtain local ips and gateways with
  3. iproute2 (called as subprocess) and netifaces (module)
  4. which provides a generic api for all os.
  5. """
  6.  
  7.  
  8. import json
  9. from subprocess import check_output
  10. from socket import AF_INET
  11.  
  12. from netifaces import gateways, interfaces, ifaddresses
  13.  
  14.  
  15. def get_local_ips():
  16.     cmd = ["ip", "-j", "-4", "a", "s", "scope", "global"]
  17.     result = json.loads(check_output(cmd, encoding="utf8"))
  18.     return [
  19.         addr["local"] for res in result
  20.         for addr in res.get("addr_info", [])
  21.     ]
  22.  
  23.  
  24. def get_default_gateways():
  25.     cmd = ["ip", "-j", "-4", "r", "s", "default"]
  26.     result = json.loads(check_output(cmd, encoding="utf8"))
  27.     return [res.get("gateway", "") for res in result]
  28.  
  29.  
  30. def get_local_ips2():
  31.     ips = []
  32.     for interface in interfaces():
  33.         if interface == "lo":
  34.             continue
  35.         for result in ifaddresses(interface).get(AF_INET, []):
  36.             ips.append(result["addr"])
  37.     return ips
  38.  
  39.  
  40. def get_default_gateways2():
  41.     ips = []
  42.     result = gateways().get("default", {}).get(AF_INET, ())
  43.     return [result[0]]
RAW Paste Data