Search code examples
pythonscapytraceroute

tracert in scapy (python)


I try to do the tracert operation in Scapy but it does not work for me, it writes me that there is an error in print (NoneType), can anyone help me solve the problem?

from scapy.all import *
from scapy.layers.inet import IP, ICMP, Ether, UDP, traceroute
TTL = 28
packet = IP(dst = '8.8.8.8') / ICMP(type = 0)
for i in range(TTL):
    packet[IP].ttl = i + 1
    ans = sr1(packet, timeout = 2, verbose = 0)
    print(ans[IP].src)

Solution

  • You cannot assume that every ICMP echo request you send will get an answer. If you don't receive an answer then sr1 returns None after a 2 seconds delay. This explains the error message because then ans[IP].src is incorrect since ans is None. Therefore you have to handle that situation in your code:

    from scapy.all import IP, ICMP, sr1
    TTL = 28
    packet = IP(dst = '8.8.8.8') / ICMP(type = 0)
    for i in range(TTL):
        packet[IP].ttl = i + 1
        ans = sr1(packet, timeout = 2, verbose = 0)
        if ans is None:
            print('no response...')
        else:
            print(ans[IP].src)