Skip to content

Instantly share code, notes, and snippets.

@whiler
Created August 6, 2019 04:17
Show Gist options
  • Save whiler/6234188e6a28f82b6f8ecfb0ac8c46a2 to your computer and use it in GitHub Desktop.
Save whiler/6234188e6a28f82b6f8ecfb0ac8c46a2 to your computer and use it in GitHub Desktop.
traceroute implementation in Python
#!/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)
@whiler
Copy link
Author

whiler commented Aug 6, 2019

1 * 0.702s
2 96.44.162.49 0.011s
3 69.12.70.234 0.000s
4 213.248.71.105 0.011s
5 213.248.67.111 0.011s
6 152.195.76.133 0.011s
7 152.195.76.204 0.011s
8 152.195.76.133 0.011s
9 93.184.216.34 0.011s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment