pythonpython-3.xdpkt

Convert binary/hex encoded string to an integer


Hi sorry if this is a duplicate. Have done my best to look for an answer
BACKGROUND:
I am using dpkt to try and read the src and destination ip of packets in a PCAP file. The raw data in the file is stored simply as bytes: c0 a8 00 28 => 192 168 0 40. Perfect if I was using C all would be good I could just rip this out of the file, unfortunately I am having to use python, specifically the dpkt library:
PROBLEM:
When I try to print out the ip using:

import dpkt
file = open("./PCAPfiles/somerandom.pcap", "rb")
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    ip = eth.data
    print(ip.src)
    break

OUTPUT: b'\xc0\xa8\x00('
you can see its the data I want, (c0 a8 00 28 => 192 168 0 40) with "(" mapping to 40 in the ascii lookup table.
QUESTION:
How can I consistently turn b'\xc0\xa8\x00(' into c0 a8 00 28, if there is a nice function that would be nice, but if I just have to manually build a string parser that is fine.


Solution

  • You can use bytearray() and hex() to get the hexadecimal value from an array of byte values:

    s = b'\xc0\xa8\x00('
    print(bytearray(s).hex())
    

    Output:

    c0a80028
    

    Also, using a list comprehension can be much more clear solution, as it outputs directly the int values expected:

    s = b'\xc0\xa8\x00('
    print([i for i in bytearray(s)])
    

    Output

    [192, 168, 0, 40]