C++ 如何将标准 IP 地址格式字符串转换为 hex 和 long?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/491060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:38:35  来源:igfitidea点击:

How to convert standard IP address format string to hex and long?

c++formatip-address

提问by Niko Gamulin

Does anyone know how to get the IP address in decimal or hex from standard IP address format string ("xxx.xxx.xxx.xxx")?

有谁知道如何从标准 IP 地址格式字符串(“xxx.xxx.xxx.xxx”)中获取十进制或十六进制的 IP 地址?

I've tried to use the inet_addr() function but didn't get the right result.

我尝试使用 inet_addr() 函数,但没有得到正确的结果。

I tested it on "84.52.184.224"

我在“84.52.184.224”上测试过

the function returned 3770168404 which is not correct (the correct result is 1412741344).

函数返回 3770168404,这是不正确的(正确结果是 1412741344)。

Thanks!

谢谢!

回答by Paul Dixon

You have just got the bytes reversed from what you expected - they are in network byte order

您刚刚获得了与您预期相反的字节 - 它们按网络字节顺序排列

3770168404 = 0xE0 B8 34 54     network byte order
               |         |
                \       /
                 \     /
                  \   /
                   \ /
                   /\
                  /  \   
                 /    \
                /      \
               |        |
1412741344 = 0x54 34 B8 E0     machine order

You could use ntohl()convert from network order to machine order.

您可以使用ntohl()从网络顺序转换为机器顺序。

回答by Hymanson

The htonl, htons, ntohl, ntohs functions can be used to convert between network and local byte orders.

htonl、htons、ntohl、ntohs 函数可用于在网络和本地字节顺序之间进行转换。

回答by soulmerge

The returned result is correct, the bytes are ordered in network byte order

返回结果正确,字节按网络字节序排列

84 => 0x54
52 => 0x34
184 => 0xb8
224 => 0xe0
0xe0b83454 => 3770168404

回答by John Stauffer

I think you may be running into a byte order issue. From the man page:

我认为您可能会遇到字节顺序问题。从手册页:

All Internet addresses are returned in network order (bytes ordered from left to right). All network numbers and local address parts are returned as machine byte order integer values.

所有 Internet 地址都按网络顺序返回(字节从左到右排序)。所有网络号和本地地址部分都作为机器字节顺序整数值返回。

回答by John Stauffer

Carefully check the below link:

仔细检查以下链接:

http : // msdn.microsoft.com/en-us/library/ms738563(VS.85).aspx

http : // msdn.microsoft.com/en-us/library/ms738563(VS.85).aspx