Python 3.4:未知的格式代码' x'

时间:2016-01-23 19:52:31

标签: python networking network-programming packet sniffer

我在Python3中遇到有关数据包嗅探器的问题。

版本的python:3.4

我遵循了一些有效的教程,但没有在我的电脑上。 此代码必须获取mac地址,将其转换为字符串,并且在main()方法中应该打印到目标mac,source mac和protocol。

代码:sniffer_demo.py

import socket
import struct
import textwrap

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

    while True:
        raw_data, addr = conn.recvfrom(65536)
        # one's and zero's put to the method ehternet_frame
        dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
        print('\nEthernet Frame:')
        print('Destination: {}, Source: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto))


# Unpack ethernet frame
def ethernet_frame(data):
    dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14])
    return get_mac_addr(dest_mac), get_mac_addr(src_mac), socket.htons(proto), data[14:]


# Return properly formatted MAC address: (ie AA:BB:CC:DD:EE:FF)
def get_mac_addr(bytes_addr):
    bytes_str = map('{:02x}'.format, bytes_addr)
    return ':'.join(bytes_str).upper()

main()

错误是:

Traceback (most recent call last):
  File "sniffer_demo.py", line 28, in <module>
    main()
  File "sniffer_demo.py", line 11, in main
    dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
  File "sniffer_demo.py", line 19, in ethernet_frame
    return get_mac_addr(dest_mac), get_mac_addr(src_mac), socket.htons(proto), data[14:]
  File "sniffer_demo.py", line 24, in get_mac_addr
    bytes_str = map('{:02x}'.format, bytes_addr)
ValueError: Unknown format code 'x' for object of type 'str'

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

在尝试重现时,您的代码似乎完全按预期工作。我没有看到任何shebang线。您确定使用# python3.4 snif2.py执行了吗?

Ethernet Frame: Destination: A4:17:31:xx:xx:xx, Source: 00:0C:F6:xx:xx:xx, Protocol: 8 Ethernet Frame: Destination: 00:0C:F6:xx:xx:xx, Source: A4:17:31:xx:xx:xx, Protocol: 8 ^CTraceback (most recent call last): File "snif2.py", line 27, in <module> main() File "snif2.py", line 9, in main raw_data, addr = conn.recvfrom(65536) KeyboardInterrupt 的示例输出:

{{1}}

答案 1 :(得分:0)

将Python更新到3.6版。