ICMP数据包嗅探未接收任何数据(Black Hat Python手册)

ICMP数据包嗅探未接收任何数据(Black Hat Python手册),python,python-3.x,sockets,packet-sniffers,icmp,Python,Python 3.x,Sockets,Packet Sniffers,Icmp,我在《黑帽Python》第3章中找到了这段代码片段。网络:原始套接字和嗅探: import socket import os host = "x.x.x.x" # Host to listen on # Create a raw socket and bind it to the public interface if os.name == "nt": socket_protocol = socket.IPPROTO_IP els

我在《黑帽Python》第3章中找到了这段代码片段。网络:原始套接字和嗅探:

import socket
import os

host = "x.x.x.x"        # Host to listen on

# Create a raw socket and bind it to the public interface
if os.name == "nt":
    socket_protocol = socket.IPPROTO_IP
else:
    socket_protocol = socket.IPPROTO_ICMP
    
sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
sniffer.bind((host, 0))
sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)     # We want the IP headers included in the capture
# if we're using Windows, we need to send an IOCTL
# to set up promiscuous mode
if os.name == "nt":
    sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
print(sniffer.recvfrom(65565))      # Read in a single packet

# If we're using Windows, turn off promiscuous mode
if os.name == "nt":
    sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
当我执行ping google.com时,上面的代码应该捕获第一个ping数据包,但是会无限期地等待
打印行中的数据包(sniffer.recvfrom(65565))

我尝试使用
host
作为我机器的本地ip和localhost,并尝试更改缓冲区大小,如图中所示。但这并不好

当我设置
host=”“
并执行
ping 127.0.0.1
操作时,我会工作,但在ping其他URL时不会工作

谁能告诉我怎么了


我使用的是Python 3.8.2和Ubuntu 18.04。

问题实际上与代码无关,而是兼容性问题,ping更现代的服务器是通过
IPv6
完成的,而代码只拾取
IPv4
ICMP数据包。一个简单的解决方案是通过以下方式将ping限制为
IPv4

ping -4 google.com
IPv6
的嗅探器只需要对
IPv4
版本进行一些小的更改,如下所示:

import socket
import os

host = ""       # Host to listen on

# Create a raw socket and bind it to the public interface
if os.name == "nt":
    socket_protocol = socket.IPPROTO_IPV6
else:
    socket_protocol = socket.IPPROTO_ICMPV6
    
sniffer = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket_protocol)
sniffer.bind((host, 0))
sniffer.setsockopt(socket.IPPROTO_IPV6, socket.IP_HDRINCL, 1)       # We want the IP headers included in the capture
# if we're using Windows, we need to send an IOCTL
# to set up promiscuous mode
if os.name == "nt":
    sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
print(sniffer.recvfrom(65565))      # Read in a single packet

# If we're using Windows, turn off promiscuous mode
if os.name == "nt":
    sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

当您ping其他IP/url时,它会将请求直接发送到其他IP/ulr,并且没有理由发送到您的本地IP。据我所知,捕获数据包的工具需要库(
数据包捕获
)。我还必须在LinuxMint(基于Ubuntu18.04)上以
root
(使用
sudo
)的身份运行代码。我使用了
0.0.0.0
来监听我所有的网卡(
LAN
WiFi
),我得到了一些结果。@furas感谢您的评论,我得到了解决方案,因为您告诉我它可以工作。我分析了为什么它在某些情况下有效,这让我找到了答案。