Convert MAC to hex howto

Discussion in 'Python' started by Johannes Graumann, Oct 7, 2012.

  1. Dear all,

    I'm trying to convert
    '00:08:9b:ce:f5:d4'
    to
    '\x00\x08\x9b\xce\xf5\xd4'
    for use in magic packet construction for WakeOnLan like so:
    wolsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    wolsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    wolsocket.sendto('\xff'*6 + '\x00\x08\x9b\xce\xf5\xd4'*16,
    (expectedlanbroadcast, 80))

    This is what I came up whith, but I remain puzzled on how to preserver the
    leading '\h' ... thanks for any hint

    expectedservermac = '00:08:9b:ce:f5:d4'
    hexcall = str.split(expectedservermac,":")
    hexcall.insert(0,'')
    hexcall = "\\x".join(hexcall).decode('string_escape')

    Thanks for any pointers.

    Sincerely, Joh
    Johannes Graumann, Oct 7, 2012
    #1
    1. Advertising

  2. Johannes Graumann

    Paul Rubin Guest

    Johannes Graumann <> writes:
    > '00:08:9b:ce:f5:d4'
    > ...
    > hexcall = "\\x".join(hexcall).decode('string_escape')


    I think it's best not to mess with stuff like that. Convert to integers
    then convert back:

    mac = '00:08:9b:ce:f5:d4'
    hexcall = ''.join(chr(int(c,16)) for c in mac.split(':'))
    Paul Rubin, Oct 7, 2012
    #2
    1. Advertising

  3. Paul Rubin wrote:

    > Johannes Graumann <> writes:
    >> '00:08:9b:ce:f5:d4'
    >> ...
    >> hexcall = "\\x".join(hexcall).decode('string_escape')

    >
    > I think it's best not to mess with stuff like that. Convert to integers
    > then convert back:
    >
    > mac = '00:08:9b:ce:f5:d4'
    > hexcall = ''.join(chr(int(c,16)) for c in mac.split(':'))


    Thanks to you as well!

    Joh
    Johannes Graumann, Oct 7, 2012
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    10
    Views:
    6,109
    Neredbojias
    Aug 19, 2005
  2. Bengt Richter
    Replies:
    6
    Views:
    439
    Juha Autero
    Aug 19, 2003
  3. MRAB

    Re: Convert MAC to hex howto

    MRAB, Oct 7, 2012, in forum: Python
    Replies:
    0
    Views:
    173
  4. Johannes Graumann

    Re: Convert MAC to hex howto

    Johannes Graumann, Oct 7, 2012, in forum: Python
    Replies:
    0
    Views:
    156
    Johannes Graumann
    Oct 7, 2012
  5. Peter Otten

    Re: Convert MAC to hex howto

    Peter Otten, Oct 7, 2012, in forum: Python
    Replies:
    0
    Views:
    173
    Peter Otten
    Oct 7, 2012
Loading...

Share This Page