note 54679 modified in function.ip2long by danbrown

From: Date: Fri, 05 Dec 2008 13:42:15 +0000
Subject: note 54679 modified in function.ip2long by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-147697@lists.php.net to get a copy of this message
Note: ip2long and long2ip do not function as the c linux functions inet_addr and inet_ntoa. They store the long in reverse byte order (little endian vs big endian i guess). For example you send 10.0.0.1 to inet_ntoa you take the long from the result and you pass it to long2ip you get 1.0.0.10. You won't run into this issue unless you use a database both from c linux programs and php scripts. My first idea was to reverse the long, but unfortunatley the long was stored as unsigned and i got a lot of problems doing calculations with it (some operations would work well others not; probably it was stored as float i do not know for sure...) So my solution was <?php function str_rev_ip($str) { $ar=explode(".",$str); return "$ar[3].$ar[2].$ar[1].$ar[0]"; } ?> and i take the result from inet_ntoa and parse it as str_rev_ip(long2ip($var)) --was-- Note: ip2long and long2ip do not function as the c linux functions inet_addr and inet_ntoa. They store the long in reverse byte order (little endian vs big endian i guess). For example you send 10.0.0.1 to inet_ntoa you take the long from the result and you pass it to long2ip you get 1.0.0.10. You won't run into this issue unless you use a database both from c linux programs and php scripts. My first ideea was to reverse the long, but unfortunatley the long was stored as unsigned and i got a lot of problems doing calculations with it (some operations would work well others not; probably it was stored as float i do not know for sure...) So my solution was function str_rev_ip($str) { $ar=explode(".",$str); return "$ar[3].$ar[2].$ar[1].$ar[0]"; } and i take the result from inet_ntoa and parse it as str_rev_ip(long2ip($var)) http://php.net/manual/en/function.ip2long.php

« previous php.notes (#147697) next »