python - 尽管绑定了套接字,Python Packet Sniffer 不输出任何内容
问题描述
我正在阅读新的波士顿 Python 网络数据包嗅探器教程系列。但是我认为他是在 Linux 上做的,这就解释了为什么很多在 Windows 上做的人都会遇到包括我在内的问题。
我用 AF_INET 替换了 socket.AF_Socket,用 socket.IPPROTO_IP 替换了 socket.htons(3),所以它可以在 Windows 上运行。然后我遇到了 OSError: [WinError 10022] An invalid argument is provided 错误。经过研究,我发现我必须在使用 .recvfrom 函数之前绑定套接字。现在它编译得很好,但在视频中,他在6:12刷新了浏览器,当我的输出窗口保持空白时,他可以看到所有流量。感谢您的帮助。
import socket
import struct
import textwrap
def main():
# Create socket and make sure endian is handled
host = socket.gethostname()
port = 9999
conn = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
conn.bind((host, port))
while True:
# Whenever these is data coming through store it in raw_data and addr variable
raw_data, addr = conn.recvfrom(65536)
# Extract data from raw_data variable
dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
print('\nEthernet Frame:')
print('Destination: {}, Source: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto))
# Unpack ethernet frame
def ethernet_frame(data):
# Resolve endian transformation.Structure is 6 bytes for destination and source so it requires 6s and signed int
# for protocol which is shown with H that has 2 bytes length
# Sniff 14 bytes in packet starting from the beginning byte.
dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14])
# Make extracted data human readable by formatting it.Convert to check that if we are big or little endian based
# on the task. So it takes bytes and make it compatible so it is human readable
return get_mac_addr(dest_mac), get_mac_addr(src_mac), socket.htons(proto), data[14:]
# Return properly formatted MAC Address (ie AA:BB:CC:DD:EE:FF)
def get_mac_addr(bytes_addr):
# Run through the Mac Address
bytes_str = map('{:02x}'.format, bytes_addr)
# Return properly formatted MAC Address
return ':'.join(bytes_str).upper()
main()