Search code examples
pythontcpscapy

How can I receive two answers to one packet using scapy?


I am developing something like TCP Server in Python using scapy. A typical TCP server should work like this.

  • First, it waits for an incoming SYN packet by calling sniff.
  • Second, it sends a SYNACK and waits for an ACK response in a single call, this is done with sr1 call.
  • Third, it waits for an incoming packet with a client request by calling sniff.

But the problem is that request packet can arrive between the sr1 and second sniff and thus get lost, because sniff does not capture packets that arrived before it is called. (I can see with Wireshark that a packet is arriving).

How can I send SYNACK and receive both ACK and a request in one call, 'atomically'?

(In a typical TCP connection, the client will resend the packet with the request after some timeout, but according to the conditions of my task there is no re-sending of packets, packets cannot be lost).


Solution

  • You can create a scapy socket and call sr1 or sniff on it. For instance

    from scapy.config import conf
    sock = conf.L3socket()
    sock.sr1(....)
    sock.sniff(...)
    

    Because it is the same socket, you won't be losing any packets