Last active
July 4, 2017 02:29
-
-
Save mpontillo/20bf8a5cb3e5ba1573f50f1055f1c370 to your computer and use it in GitHub Desktop.
Look up the IP addresses and source interface for each given host.
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
#!/usr/bin/env python3 | |
from collections import OrderedDict | |
import socket | |
import sys | |
def print_route_lookup(host, addrinfo): | |
endpoints = set() | |
for info in addrinfo: | |
if int(info[1]) == socket.SOCK_DGRAM: | |
endpoints.add((info[0], info[4])) | |
for endpoint in endpoints: | |
af = int(endpoint[0]) | |
sock = socket.socket(int(endpoint[0]), socket.SOCK_DGRAM) | |
endpoint_address = endpoint[1] | |
peername = endpoint_address[0] | |
description = peername | |
local_address = "0.0.0.0" if af == socket.AF_INET else "::" | |
try: | |
sock.bind((local_address, 0)) | |
sock.connect((peername, 7)) | |
sockname = sock.getsockname() | |
own_ip = sockname[0] | |
if host != peername: | |
description = "%s at %s" % (host, peername) | |
print("%s via %s" % (description, own_ip)) | |
except OSError as e: | |
# Probably "can't assign requested address", which probably means | |
# we tried to connect to an IPv6 address, but IPv6 is not | |
# configured. | |
print("%s - no route to host" % description, file=sys.stderr) | |
if __name__ == "__main__": | |
lookups = OrderedDict() | |
for arg in sys.argv[1:]: | |
try: | |
lookups[arg] = socket.getaddrinfo(arg, 443) | |
except socket.gaierror: | |
print("%s - name lookup failed" % arg, file=sys.stderr) | |
for host in lookups: | |
print_route_lookup(host, lookups[host]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment