python - Python数据包嗅探器故障排除
问题描述
我正在为 python 中的数据包嗅探器脚本尝试这种设计。我都打出来了。这是简短版本的样子:
#packet sniffer for linux in python
import socket, sys
from struct import*
#A function that converts a string of 6 characters of ethernet address into dash seperated hex string
def ethernet_address (string):
new_String = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(string(0)), ord(string(1)), ord(string(2)), ord(string(3)), ord(string(4)), ord(string(5)))
return new_String
#Section that creates the socket
#This is the section giving me errors
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(0x0003))
except socket.error as msg:
print ("Socket could not be created, Error : ")
print (msg)
sys.exit()
#end of error section
#recieve a packet
while True:
packet = sock.recvfrom(60000)
#packet string from tuple
packet = packet[0]
#parse ethernet header
ether_length = 14
ether_Header = packet[:ether_length]
ether = unpack('!6s6sh', ether_Header)
ether_protocol = socket.ntohs(ether[2])
print ("Destination MAC: " + ethernet_address(packet[0:6]) + "Source MAC: " + ethernet_address(packet[6:12]) + " Protocol: " + str(ether_protocol))
#This section handles parsing IP packets
if ether_protocol == 8:
#Parse the IP header
#take the first 20 character from the header
ip_header = packet[ether_length:20 + ether_length]
#now unpack
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xf
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
source_address = socket.inet_ntoa( iph[8] )
destination_address = socket.inet_ntoa( iph[9] )
print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol) + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )
#This section handles parsing TCP packets
if protocol == 6 :
print("TCP packet")
#This section Handles parsing ICMP packets
elif protocol == 1:
print("ICMP packet)
#This section handles parsing UDP
elif protocol == 17:
print("UDP Packet")
else:
print("Protocol is something other than UDP, ICMP, or TCP")
当我尝试在 Ubuntu for windows 上运行它时,sudo
我得到了这个错误:[Errno 93] Protocol not supported
我试过换行:sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(0x0003))
至:sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
但这给了我另一个错误:[Errno 97] Address family not supported by protocol
sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
如果我使用我什至通过确保我有 wsl version2 并且它仍然给我这个错误,也会发生同样的事情。我能做些什么呢?
解决方案
推荐阅读
- laravel - 数字海洋水滴的高内存使用率
- unix - 使用 awk 将字段从第 n 个重新排序到 NF-1
- reactjs - 使用 React Router 的 React Styleguide
- python - Pandas:根据从其他列中提取的子字符串截断列中的字符串(Python 3)
- windows - 写入已安装的 Windows 共享
- python - Keras ImageDataGenerator 验证拆分未从洗牌数据集中选择
- c# - C# wrapper Java 库生成奇怪的代码
- java - 线程“main”java.lang.IllegalStateException 中的异常:驱动程序可执行文件是一个目录
- python - 网格根据最大的小部件调整线条的大小
- javascript - 通过调用 javascript 类的对象来调用内部函数。我想通过调用类对象来打印优先队列数组