Search code examples
ipscapyicmp

How to measure time from send and receive in scapy?


I write such code in scapy to make simple ping - nothing special but it looks promising.

def ping(ip):
    answer = sr1(IP(dst=ip) / ICMP())

How can I measure travel time from send to receive in scapy. Question is very simple but also very essential to learn it. I searching some solution in internet and documentation but without effect.

Can you help with it?

Full code look like this but measure ping is too long.

import time

from scapy.layers.inet import ICMP, IP
from scapy.sendrecv import sr1, sr


def ping(ip):
    packet = IP(dst=ip) / ICMP()
    t0 = time.perf_counter()
    answer = sr1(packet)
    t1 = time.perf_counter()
    print(t1 - t0)

    answer.show()
    answer[ICMP].show()

ping('192.168.1.1')

Result of t1 - t0 = 0.12669169999999985s. ping.exe = 4ms so something wrong.


Solution

  • You should use the sent_time parameter. For instance, if you are using sr, you can do:

    ans, unans = sr(IP(dst="www.google.com")/ICMP())
    timestamp = ans[0][1].time - ans[0][0].sent_time
    

    In your example:

    packet = IP(dst=ip)/ICMP()
    a = sr1(packet)
    timestamp = a.time - packet.sent_time
    

    Works too