简体   繁体   中英

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

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

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

I tested it on "84.52.184.224"

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

Thanks!

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.

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

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

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

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.

Carefully check the below link:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM