简体   繁体   English

如何在Python中从TCP套接字读取完整的IP帧?

[英]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. 我需要使用Python从TCP流套接字读取完整的(原始)IP帧。 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. 我一直在研究Python中的原始套接字,但我遇到了一些问题。 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)? 那么,我如何从现有的TCP套接字(在Python中)读取整个IP框架(包括标题)?

Preferably I'd like to use only standard libraries. 我最好只使用标准库。 Also, I am on a Linux host. 另外,我在Linux主机上。

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. 如果您不介意使用不属于标准库的Scapy ,并且不要求超高速,则可以使用其sniff功能。 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. 您可以使用count=0在不同的线程或进程中运行sniff,并且如果您希望它永远运行,则将收到的数据包粘贴在队列中。 Just make sure that you put str(pkt) on the queue. 只需确保将str(pkt)放在队列中。 I've seen weird things happen when putting scapy packets on multiprocessing.Queue s. 我已经看到将scapy数据包放在multiprocessing.Queue上时会发生奇怪的事情。

Debian and Ubuntu both have Scapy in their apt repositories. Debian和Ubuntu都在他们的apt资源库中安装了Scapy。 I don't know about rpm distros. 我不知道rpm发行版。 It's pretty easy to install from source though: ./setup.py install . 从源代码安装非常简单: ./setup.py install

你应该尝试scapy

也许pylibpcap可以做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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