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.
CodePudding user response:
Just convert each byte to an int then to a string as follows:
b = b'\xc0\xa8\x00('
print(' '.join(map(str, list(b))))
Output:
192 168 0 40
CodePudding user response:
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]
CodePudding user response:
Of course the minute after I post a question I find the answer, if I use the list() function it solves all my issues:
for integer in list(ip.src):
print(integer)
OUTPUT: 192 168 0 40 Perfect, sometimes writing out your question can help you find an answer.