gpt4 book ai didi

python - ICMP数据包嗅探未接收到任何数据(Black Hat Python书)

转载 作者:行者123 更新时间:2023-12-03 12:02:30 25 4
gpt4 key购买 nike

我从第3章黑帽Python 这本书中看到了此代码片段。网络:原始套接字和嗅探:

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数据包,但是 无限地等待print(sniffer.recvfrom(65565))行中的数据包
我尝试使用 host作为机器的本地ip并使用localhost,并尝试更改缓冲区大小,如 similar question所示。但这不好。
当我设置 host = ""并执行 ping 127.0.0.1时,我可以工作,但在ping其他URL时却不能。
有人可以告诉我怎么了吗?
我正在使用Python 3.8.2和Ubuntu 18.04。

最佳答案

问题实际上与代码无关,它是兼容性问题,通过IPv6对更现代的服务器执行ping操作,而代码仅选择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)

关于python - ICMP数据包嗅探未接收到任何数据(Black Hat Python书),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63204996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com