Skip to content

Instantly share code, notes, and snippets.

@zhongWJ
Forked from jcjones/python-traceroute.py
Last active January 17, 2023 06:34
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save zhongWJ/4783e74f04f7832d749f65fcd821d813 to your computer and use it in GitHub Desktop.
Save zhongWJ/4783e74f04f7832d749f65fcd821d813 to your computer and use it in GitHub Desktop.
#On macOS Mojave, this script must run in root, otherwise you will
#get a runtime error due to "No permission" error when create raw socket
import socket
import io
import struct
import sys
class flushfile(io.FileIO):
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
sys.stdout = flushfile(sys.stdout)
def main(dest_name):
dest_addr = socket.gethostbyname(dest_name)
port = 55285
max_hops = 30
ttl = 1
while True:
rec_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
timeout = struct.pack("ll", 5, 0)
rec_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout)
rec_socket.bind(("", port))
sys.stdout.write(" %d " % ttl)
send_socket.sendto(bytes("", "utf-8"), (dest_name, port))
curr_addr = None
curr_name = None
finished = False
tries = 3
while not finished and tries > 0:
try:
_, curr_addr = rec_socket.recvfrom(512)
finished = True
curr_addr = curr_addr[0]
try:
curr_name = socket.gethostbyaddr(curr_addr)[0]
except socket.error:
curr_name = curr_addr
except socket.error as err:
tries -= 1
sys.stdout.write("* ")
send_socket.close()
rec_socket.close()
if not finished:
pass
if curr_addr is not None:
curr_host = "%s (%s)" % (curr_name, curr_addr)
else:
curr_host = ""
sys.stdout.write("%s\n" % (curr_host))
ttl += 1
if curr_addr == dest_addr or ttl > max_hops:
break
if __name__ == "__main__":
main("baidu.com")
@joaquimds
Copy link

This is great, thanks! Do you know why rec_socket has to be SOCK_RAW? I tried it with SOCK_DGRAM on OSX 10.14 and it seems to work, but I don't fully understand what's going on.

@noath
Copy link

noath commented Apr 26, 2021

Why do we need lines 56-57?

@ganti-sharan
Copy link

Hello, I keep getting * as output

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