为什么inet_ntoa和inet_ntop是“ reverse”?字节? [英] Why do inet_ntoa and inet_ntop "reverse" the bytes?

查看:129
本文介绍了为什么inet_ntoa和inet_ntop是“ reverse”?字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题,令我惊讶的是,我今天遇到了一个问题。

This is a rather basic problem with which, to my surprise, I've had a problem today.

在我看来,inet_pton和inet_ntoa正在逆转

It looks to me like inet_pton and inet_ntoa are reversing the bytes of the IP address they're given:

DWORD IP;
inet_pton(AF_INET, "192.168.0.1", &IP);
printf("%08X\n", IP);

这将打印 0100A8C0 。而且,如果我们分解字节,则为
01.00.A8.C0 = 1.0.168.192

This will print 0100A8C0. And well, if we break down the bytes, it's 01.00.A8.C0 = 1.0.168.192.

类似地:

IP = 0x7F000001;
struct in_addr ia;
ia.S_un.S_addr = IP;

printf("%s\n", inet_ntoa(ia));

给我 1.0.0.127

首先想到的是字节序,但是我已经阅读了MSDN文档( 1 2 ),并且未提及字节顺序;对我来说似乎很奇怪,这些函数会随意决定使用其中一种表示法,而未在规范中明确说明。

The first thing that comes to mind is endianness, but I've read the MSDN documentation (1 and 2) and the byte order is not mentioned; it seems weird to me that these functions would arbitrarily decide to use one of the notations without the specification clearly stating that.

发生了什么事?

推荐答案

字节顺序原因。

这些函数不是产生可读整数,而是设置一个准备好在线上发送的32位数量。 IPv4需要大端字节序,所以我敢打赌,如果您执行 printf(%02X\n,((char *)& IP)[0])); ,您将获得 C0

The whole point of these functions is not to produce a "readable" integer, but to set a 32-bit quantity that is ready to be shipped out on the wire. IPv4 requires big-endian ordering, so I would wager that if you did printf("%02X\n", ((char *)&IP)[0]));, you'd get C0.

这篇关于为什么inet_ntoa和inet_ntop是“ reverse”?字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆