简体   繁体   English

Python 原始 Sockets (Windows):嗅探以太网帧

[英]Python Raw Sockets (Windows): Sniffing Ethernet Frames

I have seen several examples of creating sockets to sniffing for IP Packets, for example using:我已经看到了几个创建 sockets 以嗅探 IP 数据包的示例,例如使用:

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)

What I am trying to achieve, is sniffing for Ethernet Frames and analysing the data received in Windows.我想要实现的是嗅探以太网帧并分析在 Windows 中接收到的数据。 The packets I am interested in are PPPoE Frames not containing IP .我感兴趣的数据包是不包含 IP 的 PPPoE 帧

In Linux (using python) I was able to achieve this using:Linux (使用 python)中,我能够使用以下方法实现此目的:

s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(3))
s.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, struct.pack("%ds"%(len("eth0")+1,),"eth0"))
while condition:
    pkt = s.recvfrom(1500)
    addToQueue(filter(pkt))

Now due to the differences betweeen linux sockets and WinSock2 API, I am having the following compatibility issues:现在由于 linux sockets 和 WinSock2 API 之间的差异,我遇到了以下兼容性问题:

  • There is no IN package for windows. windows 没有 IN package。 That means the SO_BINDTODEVICE is not present.这意味着SO_BINDTODEVICE不存在。 How do I sniff everything coming on eth0 interface?如何嗅探 eth0 接口上的所有内容?
  • What should I use for protocol option in socket() constructor as I dont want to limit it to IPPROTO_IP.我应该在 socket() 构造函数中使用什么协议选项,因为我不想将它限制为 IPPROTO_IP。

Can anyone point me to the right direction?谁能指出我正确的方向? I went through similar questions but none of them really solved my problem as they were all concerned with IP Packet sniffing我遇到了类似的问题,但没有一个真正解决了我的问题,因为他们都关心 IP 数据包嗅探

Note: I know libraries like Scapy could be used for sniffing, but it loses packets if we are trying to do any elaborate filtering (or use the prn function) and does not suit what I am trying to do.注意:我知道像 Scapy 这样的库可以用于嗅探,但是如果我们尝试进行任何精细过滤(或使用 prn 函数)并且不适合我想要做的事情,它会丢失数据包。 Raw sockets fit my need perfectly.原始 sockets 完全符合我的需要。

I can't verify this without a Windows box but I think all you need is...如果没有 Windows 盒子,我无法验证这一点,但我认为你需要的只是......

HOST = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_RAW)
s.bind((HOST, 0))
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
while condition:
    pkt = s.recvfrom(1500)
    addToQueue(filter(pkt))

Additionally, I'd recommend that you look in to using something like pypcap (or another libpcap wrapper) instead.此外,我建议您考虑改用 pypcap(或另一个 libpcap 包装器)之类的东西。

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

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