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

using python to determine dot1x protocol type in ethernet header

我正在使用 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 文档中检查字符串格式 specs