Unix 十六进制转储中的字节顺序

发布于 2024-08-11 22:29:58 字数 432 浏览 5 评论 0原文

以下 *nix 命令将 IP 和端口 (127.0.0.1:80) 的十六进制表示形式传送到 hexdump 命令中。

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

-e 标志允许使用任意格式来解析输入。在本例中,我们将 IP 的前三个八位字节解析为无符号十进制,后跟一个点。最后一个八位位组也被解析为无符号十进制,但后面跟着一个冒号。最后——这就是问题所在——端口的 2 个字节被解析为单个无符号十进制,后跟换行符。

根据执行此命令的系统的字节顺序,结果会有所不同。大端系统将正确显示端口 80;而小尾数系统将显示端口 20480。

有没有什么方法可以操作 hexdump 以了解尾数,同时仍然允许通过 -e 进行任意格式规范?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羁绊已千年 2024-08-18 22:29:58

我不知道可以用 hexdump 来完成,但这很简单
in perl:

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

您可以调整它以获得您想要的格式。 ('说'
需要 perl 5.10。使用 print 来表示 perl < 5.10)

(向那些希望投反对票的人澄清,因为我没有
“回答问题”。我建议OP更换
带有 Perl 的十六进制转储。如果必须的话,请投反对票。)

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文