Mr. Shickadance
Mr. Shickadance

Reputation: 5483

How to read complete IP frames from TCP socket in Python?

I need to read a complete (raw) IP frame from a TCP stream socket using Python. Essentially I want an unmodified frame just as if it came off the physical line, including all the header information.

I have been looking into raw sockets in Python but I have ran into some issues. I don't need to form my own packets, I simply need to read and forward them verbatim.

So, how can I read an entire IP frame (incl. header) from an existing TCP socket (in Python)?

Preferably I'd like to use only standard libraries. Also, I am on a Linux host.

Thanks!

Upvotes: 3

Views: 2973

Answers (3)

nmichaels
nmichaels

Reputation: 51029

If you don't mind using Scapy, which is not part of the standard library, and super speed isn't a requirement, you can use its sniff function. It takes a callback. Something like:

pkts_rxd = []
def process_and_send(pkt):
    pkts_rxd.append(pkt)
    sendp(pkt, 'eth1')
sniff(prn=process_and_send, iface='eth0', count=100)

You can run the sniff in a different thread or process, with count=0 and stick the received packets on a queue if you want it to run forever. Just make sure that you put str(pkt) on the queue. I've seen weird things happen when putting scapy packets on multiprocessing.Queues.

Debian and Ubuntu both have Scapy in their apt repositories. I don't know about rpm distros. It's pretty easy to install from source though: ./setup.py install.

Upvotes: 3

Sjoerd
Sjoerd

Reputation: 75679

Maybe pylibpcap can do that.

Upvotes: 0

jliendo
jliendo

Reputation: 390

You should try scapy.

Upvotes: 0

Related Questions