Endianness in Unix hexdump
Asked Answered
C

1

8

The following *nix command pipes a hex representation of an IP and port (127.0.0.1:80) into the hexdump command.

printf "\x7F\x00\x00\x01\x00\x50" | hexdump -e '3/1 "%u." /1 "%u:" 1/2 "%u" "\n"'

The -e flag allows an arbitrary format to parse the input. In this case, we are parsing the first three octets of the IP into unsigned decimals followed by a dot. The final octet is also parsed into an unsigned decimal but it is followed by a colon. Finally -- and this is where the problem lies -- the 2 bytes for the port are parsed as a single unsigned decimal followed by a newline.

Depending on the endianness of the system executing this command, the result will differ. A big-endian system will properly show port 80; whereas a little-endian system will show port 20480.

Is there any way to manipulate hexdump to be aware of endianness while still allowing the arbitrary format specification via -e?

Corettacorette answered 20/11, 2009 at 16:31 Comment(2)
I assume that it's not acceptable to have to prepare the input by swapping the last two bytes if the platform is little-endian, since you're asking the question?Waterless
Is it looking like a byte-swap will be necessary?Corettacorette
D
6

I don't know that it can be done with hexdump, but it's easy enough in perl:

$ printf '\x00\x50' | perl -nE 'say unpack "S>"'
80
$ printf '\x00\x50' | perl -nE 'say unpack "S<"'
20480

You can tweak that to get the format you desire. ('say' requires perl 5.10. Use print for perl < 5.10)

(To clarify for the person who wishes to downvote because I didn't "answer the question". I'm suggesting that the OP replace hexdump with perl. Downvote if you must.)

Doubt answered 20/11, 2009 at 16:55 Comment(1)
I'd like to stay away from C/Perl/Python and just stick to a more tool-based approach. Perhaps an xxd alternative?Corettacorette

© 2022 - 2024 — McMap. All rights reserved.