未知格式代码“x”

Aha*_*iff 4 python python-3.x

我正在用 Python 编写一个程序,所有代码看起来都不错,除非我从终端运行程序时收到以下错误消息:

Traceback (most recent call last):
  File "packetSniffer.py", line 25, in <module>
    main()
  File "packetSniffer.py", line 10, in main
    reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
  File "packetSniffer.py", line 17, in ethernet_frame
    return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(protocol), data[14:]
  File "packetSniffer.py", line 21, in getMacAddress
    bytesString = map('{:02x}'.format, bytesAddress)
ValueError: Unknown format code 'x' for object of type 'str'
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我整个程序的代码,有人可以帮忙吗?

import struct
import textwrap
import socket

def main():
    connection = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))

    while True:
        rawData, address = connection.recvfrom(65535)
        reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
        print('\nEthernet Frame: ')
        print('Destination: {}, Source: {}, Protocol: {}'.format(reciever_mac, sender_mac, ethernetProtocol))

# Unpack ethernet frame
def ethernet_frame(data):
    reciever_mac, sender_mac, protocol = struct.unpack('! 6s 6s H', data[:14])
    return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(protocol), data[14:]

# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
    bytesString = map('{:02x}'.format, bytesAddress)
    macAddress = ':'.join(bytesString).upper()
    return macAddress

main()
Run Code Online (Sandbox Code Playgroud)

Dur*_*tta 5

在以下代码部分中,格式类型 x不需要字符串。它接受整数。然后它将整数转换为其相应的十六进制形式。

# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
    bytesString = map('{:02x}'.format, bytesAddress)
    macAddress = ':'.join(bytesString).upper()
Run Code Online (Sandbox Code Playgroud)

因此,如果您的 byteAddress 是整数的字符串形式,那么您可以执行以下操作:

bytesAddress = '123234234'
map('{:02x}'.format, [int(i) for i in bytesAddress])
#map('{:02x}'.format, map(int, bytesAddress)) 
['01', '02', '03', '02', '03', '04', '02', '03', '04']
Run Code Online (Sandbox Code Playgroud)

此外,如果要将一对整数(以字符串形式)处理为十六进制,则首先将 `bytesAddress 转换为

[bytesAddress[i:i+2] for i in range(0, len(bytesAddress), 2)]
Run Code Online (Sandbox Code Playgroud)