Created
August 6, 2019 04:17
-
-
Save whiler/6234188e6a28f82b6f8ecfb0ac8c46a2 to your computer and use it in GitHub Desktop.
traceroute implementation in Python
This file contains 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 | |
# -*- coding: utf-8 -*- | |
# | |
import random | |
import socket | |
import time | |
def traceroute(dest, hops=64, timeout=0.7): | |
empty = bytes() | |
dest = socket.gethostbyname(dest) | |
with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as rsock: | |
rsock.settimeout(timeout) | |
rsock.bind(('', random.randint(32769, 65535))) | |
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) as wsock: | |
for i in range(hops): | |
ttl = i + 1 | |
wsock.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) | |
start = time.time() | |
wsock.sendto(empty, (dest, 33434 + i)) | |
try: | |
data, (addr, port) = rsock.recvfrom(1024) | |
except socket.timeout: | |
addr = '*' | |
yield ttl, addr, time.time() - start | |
if dest == addr: | |
break | |
if '__main__' == __name__: | |
import logging | |
logging.basicConfig(level=logging.NOTSET, format='%(message)s') | |
logger = logging.getLogger(__name__) | |
for route in traceroute('example.com'): | |
logger.debug('%d %s %0.3fs', *route) |
Author
whiler
commented
Aug 6, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment