Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reassemble TCP packets in Python?

Tags:

python

tcp

packet

How to reassemble TCP packets in Python? Is there any existing tools for this?

Thanks! :-)

like image 713
Tianyang Li Avatar asked Mar 07 '11 05:03

Tianyang Li


2 Answers

To do perform TCP reassembly you'll need to use something like pynids http://jon.oberheide.org/pynids/.

You can also build your own using pylibpcap, dpkt or scapy.

TCP reassembly is very tricky with a LOT of edge cases. I wouldn't recommend doing it yourself if you need a robust solution.

like image 143
Justin Avatar answered Oct 24 '22 17:10

Justin


Yes... the TCP protocol guarantees that the application layer will only see packets assembled and in order. Now if you are talking about building some low level interface parsing the IP packet itself, you can take a stab at it with RAW sockets which should give you access to IP header information. Here's an example:

import socket

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())

# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))

# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

# receive a package
print s.recvfrom(65565)

# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

lifted shamelessly from the python socket module documentation: http://docs.python.org/library/socket.html

like image 32
Rafael Ferreira Avatar answered Oct 24 '22 18:10

Rafael Ferreira