Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 808
Niko Gamulin Avatar asked Jan 29 '09 09:01

Niko Gamulin


3 Answers

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.

like image 135
Paul Dixon Avatar answered Nov 15 '22 07:11

Paul Dixon


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

like image 25
Jackson Avatar answered Nov 15 '22 06:11

Jackson


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

84 => 0x54
52 => 0x34
184 => 0xb8
224 => 0xe0
0xe0b83454 => 3770168404
like image 25
soulmerge Avatar answered Nov 15 '22 08:11

soulmerge