TcpStream receiving flipped int bytes

Monkey Forums/Monkey Beginners/TcpStream receiving flipped int bytes

Raudius(Posted 2015) [#1]
Hello,

I am trying to create a simple TCP client that receives information from a server written in Java.

The problem iss that when I send ints through java it receives the bytes in a flipped order such that for example if I writeInt(6), it would send:
00000000 00000000 00000000 00000110
But when I receive it in monkey with socket.ReadInt I receive:
00000110 00000000 00000000 00000000

Is there a way to fix this or will I have to flip the bytearray myself?


ziggy(Posted 2015) [#2]
Isn't this endiannes? Where's the server and client located? Is there any mixture of intel / arm or the like?


Raudius(Posted 2015) [#3]
Currently both on localhost.

I could just flip the int's bytes when sending them but I was hoping there would be a more elegant solution.


ImmutableOctet(SKNG)(Posted 2015) [#4]
Standard network byte-order is big-endian. You'll need to swap the bytes properly. For UDP, my 'publicdatastream' module has you covered, but for TCP, you're going to have to either make your own TCP-stream sub-class which handles this, or do it manually. For byte-swapping functionality, I recommend using my 'byteorder' module. That module doesn't support automatic byte-swapping like 'publicdatastream', though. One of these days, I should probably turn 'publicdatastream' into a generic class, so it can extend any 'Stream' type. That would pretty much fix your problem automatically.

You know what, I think I am going to look into making a common class for byte-swapping.

EDIT: In case you're interested, I added this class to my 'byteorder' module. It's not perfect, as I can't extend the custom 'Stream' classes, but it gets the job done. The 'EndianStreamManager' class can be treated like a normal 'Stream' class. Basically, it just wraps a 'Stream'.


Raudius(Posted 2015) [#5]
Wow thanks a lot. This will definitely help out.

When testing what I found weird though is that Strings were received in the right order while Integers were not. Any idea why that is?


ImmutableOctet(SKNG)(Posted 2015) [#6]
@Revihx: Depends on the exact encoding of the string. There's little and big endian versions of just about every string encoding over 1 byte large. In your case, it might just be a cross-platform compatibility thing. A number of platforms assume little endian, even when it's not the best option. Here's a wiki article about it, with regards to UTF16. Technically, the default's supposed to be assumed as big-endian, but that doesn't always apply.