IP addresses can't readily be sorted numerically because they are strings and the periods in the dotted-quad format common to IP addresses confuses things.Â For instance, in a sorted list, 22.214.171.124 will sort before 126.96.36.199 even though what you really want is to sort by the first octet (23 & 143), then by the second octed (16 & 45) and so on.
PHP and MySQL provide functions to convert IP addresses to sortable format.
Two functions are provided for use in MySQL query.Â When your IP addresses are stored in a database, you can pull them ready to sort.
INET_ATON() Returns the numeric value of an IP address
INET_NTOA() Returns the IP address converted from a numeric value
Remember that if you need both representations you can pull the value twice in the same query, i.e.
SELECT ip AS ip_dotted_quat,INET_ATON(ip) as ip_sortable FROM mytable
This provides a clean set of data for your PHP or other scripting code to work with.
You have similar options in PHP.
ip2long("127.0.0.1") converts the IP to a long integer.
long2ip() converts the long integer back to a dotted-quad IP address.
The online PHP manual suggests using the two in combination to validate an IP as shown here
//Â makeÂ sureÂ IPsÂ areÂ valid.Â alsoÂ convertsÂ aÂ non-completeÂ IPÂ into
//Â aÂ properÂ dottedÂ quadÂ asÂ explainedÂ below.
$ip = long2ip(ip2long("127.0.0.1")); //Â "127.0.0.1"
$ip = long2ip(ip2long("10.0.0")); //Â "10.0.0.0"
$ip = long2ip(ip2long("10.0.256")); //Â "10.0.1.0"