我要去thenewboston Python Network Packet Sniffer Tutorial Series。但是我认为他是在Linux上执行的,这解释了为什么许多在Windows上执行此操作的人都会遇到包括我在内的问题。
我将socket.AF_Socket替换为AF_INET,将socket.htons(3)替换为socket.IPPROTO_IP,以便它可以在Windows上运行。然后我遇到OSError:[WinError 10022]提供了无效的参数错误。经过研究,我发现在使用.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()