简体   繁体   中英

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!

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.Queue s.

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 .

你应该尝试scapy

也许pylibpcap可以做到这一点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM