Reputation: 526
I need an application that will do the following:
For the first and the last I'm fine. for the second I have a challenge:
Lets say that the data I've received is Year = 2020
. The message on the Wireshark (step 3), I shall see it as 2 bytes valued 07 e4
How can I do it? I've tried couple of ways, none of them provided me with the desired format.
Sample of the code:
data1 = '\xab\xcd\xef\xgh'
...
data, addr = sock.recvfrom (200)
elements = data.decode().split(",")
Date=elements[15].split("/")
Year = int(Date(2))
year = <do something with Year to convert to right format>
newMsg = data1 + year
...
newSock.sendto(newMsg.encode('charmap'), (IP, int(port)))
Python version 3.5
Upvotes: 0
Views: 104
Reputation: 16214
there seem to be a couple of issues here. first, if your data1
is really supposed to be raw bytes then you're better off declaring it as such by prefixing it with a b
, something like:
data1 = b'\xab\xcd\xef\xff'
if it comes from somewhere else, then encode it to bytes
appropriately.
for answering your main question, the struct
module has useful tools for encoding numbers as bytes in the way you want. ctypes
can also be useful, but struct
tends to be easier to use for these sorts of things:
data, addr = sock.recvfrom (200)
elements = data.decode().split(",")
date = elements[15].split("/")
year = int(date(2))
newMsg = data1 + struct.pack('!h', year)
and then you can send it with:
newSock.sendto(newMsg, (IP, int(port)))
Upvotes: 1