Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Example to obtain local ips and gateways with
- iproute2 (called as subprocess) and netifaces (module)
- which provides a generic api for all os.
- """
- import json
- from subprocess import check_output
- from socket import AF_INET
- from netifaces import gateways, interfaces, ifaddresses
- def get_local_ips():
- cmd = ["ip", "-j", "-4", "a", "s", "scope", "global"]
- result = json.loads(check_output(cmd, encoding="utf8"))
- return [
- addr["local"] for res in result
- for addr in res.get("addr_info", [])
- ]
- def get_default_gateways():
- cmd = ["ip", "-j", "-4", "r", "s", "default"]
- result = json.loads(check_output(cmd, encoding="utf8"))
- return [res.get("gateway", "") for res in result]
- def get_local_ips2():
- ips = []
- for interface in interfaces():
- if interface == "lo":
- continue
- for result in ifaddresses(interface).get(AF_INET, []):
- ips.append(result["addr"])
- return ips
- def get_default_gateways2():
- ips = []
- result = gateways().get("default", {}).get(AF_INET, ())
- return [result[0]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement