6

I am working on a program in Python and all the code looks good except when I run the program from the terminal I am getting the following error message:

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'

Here is the code for my entire program so far, would anybody be able to help?

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

1 Answer 1

7

In the following code section, format type x does not expect string. It accepts integer. It then converts integer to its corresponding hexadecimal form.

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

So if your bytestAddress is a string form of integer, then, you could do:

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

Further, if you want to process a pair of integers (in string form) to hexadecimal, then first transform `bytesAddress to

[bytesAddress[i:i+2] for i in range(0, len(bytesAddress), 2)]
Sign up to request clarification or add additional context in comments.

1 Comment

You can use python 3 to get rid of the error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.