I have to write code which communicates with a server:

The server will send me a pointer. However due to the nature of socket.recv() this pointer is of a strange type which I don't really get how to play with it. What I do want is to be able to add or subtract arbitrary addresses from the returned pointer and send them back. Due to the nature of a pointer, the bytes have to exactly be the right ones.

For a project in the past I already used bytes(string, 'utf-8') however that REALLY messed up dealing with such data. It took me extremely long to figure out, that the encoding was the problem and not my input :<

Is there a better way to do this?

The question was answered, however it seems to be unclear what the question was. So I'll clarify it now so that this may be helpful for others:

The question was how to substrace or addfrom a recieved buffer(which is in this case a pointer) and transform it back into a buffer again. (And I was really stupid not thinking about structs since I do rely on it already in my code.)

有帮助吗?

解决方案

If you want to parse a bytes() into something you can do arithmetics with, you can do

import struct
a=b'\xca\xfe\xba\xbe' # let's say I just received these bytes
struct.unpack(">I", a)
# -> (3405691582,)
struct.unpack(">I", a)[0]
# -> 3405691582
hex(struct.unpack(">I", a)[0])
# -> '0xcafebabe' - exactly what I expected.

To find out the other way and how to apply that on network communication, I'll leave to you as an exercise.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top