使用python确定以太网报头中的dot1x协议类型



我正在使用python枚举dot1x交换中的信息,但我在解析以太网协议时遇到麻烦。我知道以太网类型字段是两个字节,dot1x使用"888e"。我已经确认"888e"正在通过Wireshark传递,但我得到了以下输出。为什么显示的是"36488"而不是"888e"?

Destination MAC : 01:80:c2:00:00:03 Source MAC : c2:04:17:9c:f1:03 Protocol : 36488
Destination MAC : 01:80:c2:00:00:03 Source MAC : 08:00:27:83:5b:8b Protocol : 36488
Destination MAC : 01:80:c2:00:00:03 Source MAC : c2:04:17:9c:f1:03 Protocol : 36488
Destination MAC : 01:80:c2:00:00:03 Source MAC : 08:00:27:83:5b:8b Protocol : 36488
Destination MAC : 01:80:c2:00:00:03 Source MAC : c2:04:17:9c:f1:03 Protocol : 36488
我代码:

import socket, sys
from struct import *
#Convert a string of 6 characters of ethernet address into a dash separated hex string
def eth_addr (a) :
    b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]) , ord(a[1]) , ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5]))
    return b
#create a AF_PACKET type raw socket (thats basically packet level)
#define ETH_P_ALL    0x0003          /* Every packet (be careful!!!) */
try:
    s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))
except socket.error , msg:
    print 'Socket could not be created. Error Code : ' + str(msg[0]) + '   Message ' + msg[1]
    sys.exit()
# receive a packet
while True:
    packet = s.recvfrom(65565)
    #packet string from tuple
    packet = packet[0]
    #parse ethernet header
    eth_length = 14
    eth_header = packet[:eth_length]
    eth = unpack('!6s6sH' , eth_header)
    eth_protocol = socket.ntohs(eth[2])
    print 'Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' +  eth_addr(packet[6:12]) + ' Protocol : ' + str(eth_protocol)

这只是一个十六进制和十进制表示的问题。

36488为十六进制的8e88。此外,您正在进行ntohs()转换以获得eth_protocol,这基本上改变了字节顺序,即将888e转换为8e88

如果你想让你的程序打印十六进制数,请查看Python文档中的字符串格式规范。

最新更新