如何在Python中从TCP套接字读取完整的IP帧?
我需要使用 Python 从 TCP 流套接字读取完整的(原始)IP 帧。本质上,我想要一个未经修改的帧,就像它来自物理线路一样,包括所有标头信息。
我一直在研究 Python 中的原始套接字,但遇到了一些问题。我不需要形成自己的数据包,我只需要逐字阅读并转发它们。
那么,如何从现有的 TCP 套接字(在 Python 中)读取整个 IP 帧(包括标头)?
最好我只想使用标准库。另外,我在 Linux 主机上。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不介意使用 Scapy,它不是标准库的一部分,并且超级速度不是必需的,您可以使用其
sniff
功能。需要回调。类似于:如果您希望它永远运行,您可以使用
count=0
在不同的线程或进程中运行嗅探,并将收到的数据包粘贴到队列中。只需确保将 str(pkt) 放入队列即可。当将 scapy 数据包放入 multiprocessing.Queue 时,我发现发生了奇怪的事情。Debian 和 Ubuntu 的 apt 存储库中都有 Scapy。我不知道 rpm 发行版。从源代码安装非常容易:
./setup.py install
。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: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 onmultiprocessing.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。
You should try scapy.
也许 pylibpcap 可以做到这一点。
Maybe pylibpcap can do that.