未知的格式代码' x'

时间:2016-07-19 07:04:03

标签: 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'

到目前为止,这是我整个程序的代码,是否有人可以提供帮助?

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()

1 个答案:

答案 0 :(得分:4)

在以下代码部分中,format type 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()

因此,如果您的bytestAddress是整数的字符串形式,那么您可以这样做:

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']

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

[bytesAddress[i:i+2] for i in range(0, len(bytesAddress), 2)]