Search code examples
pythonlinuxtcpnetwork-programmingraw-sockets

TCP handshake using python RAW sockets


I am implementing a TCP handshake using python RAW sockets. The Linux kernel is however being quite annoying because it attempts to handle certain aspects of this protocol.

For example, when I send a SYN packet, the server responded with a SYN, ACK packet; to which the kernel automatically responds with a RST packet resetting the connection. I overcame this my dropping all such reset packets using the following iptable rule:

-A OUTPUT -p tcp -m tcp --sport 999 --tcp-flags RST RST -j DROP

Now I want to receive the SYN, ACK packet sent by the server and print it out. But I receive nothing when I do the following:

a = self.s.recvfrom(4096)

I suspect that the kernel is dropping the SYN, ACK before I can recv it using my socket. Does anyone know a reasonable workaround?


Solution

  • You can use libpcap, in Python it seems this module: http://pylibpcap.sourceforge.net/ or this one: https://pypi.python.org/pypi/pypcap

    With pcap you can register to receive messages from the kernel. By providing the correct filter from your application, you can receive TCP segments from the Kernel. I have used libpcap in C and I suppose you can use the indicated modules in the same way. For me this is the best solution as you can handle it from the application in a pretty standard way.

    To avoid the kernel responding with a RST, your solution with iptables looks the best one for me.