[Tutor] Converting MAC address . Need Help

Kent Johnson kent37 at tds.net
Mon Feb 27 16:45:32 CET 2006


Sudarshana KS wrote:
> 
> Hi,
> 
> I am using scapy for writing a dhcp client.
> 
> The problem i am facing is the mac address i have is in the form 
> 00:11:22:33:44:55 need to convert to '\x00\x11\x22\x33\x44\x55'
> Please help me out with this problem. The chaddr field in dhcp ( SCAPY) 
> requires '\x00\x11\x22\x33\x44\x55'  format.

If you break this down into smaller pieces it is not so hard.

Use the split() method of a string to break it into a list of substrings:
  >>> mac = '00:11:22:33:44:55'
  >>> mac.split(':')
['00', '11', '22', '33', '44', '55']

The list elements are still strings, you need to convert them to 
integers. The strings are in hexadecimal so use the optional base 
parameter to int():
  >>> int('11', 16)
17

Finally you have to convert this number to a byte of a string using chr():
  >>> chr(17)
'\x11'

I'll leave it to you to put all the pieces together. The join() method 
may be helpful as a last step, it converts a list of strings to a single 
string:

  >>> ''.join(['a', 'b', 'c'])
'abc'

Kent



More information about the Tutor mailing list