Normally you have different ways to do the same thing; often, the simpliest one is also the best one, nevertheless sometimes you have to choose different approach to reach your goal. In this case, with the use a non immediate way to store your data you'll gain disk space and CPU time.

An IPv4 address is composed by 4 integer numbers separated by dots, so in a database you can store it using a 15 bytes long varchar. Each integer can assume values in the range [0, 255].

With mysql and php you can reduce the amount of space required to store an IPv4 address using the functions inet_aton and inet_ntoa. 


These two functions work as described below (the description are taken from here http://dev.mysql.com/doc/refman/5.5/en/miscellaneous-functions.htm):

 INET_ATON(expr)

Given the dotted-quad representation of an IPv4 network address as a string, returns an integer that represents the numeric value of the address in network byte order (big endian). INET_ATON() returns NULL if it does not understand its argument.

mysql> SELECT INET_ATON('10.0.5.9');

        -> 167773449

For this example, the return value is calculated as 10×2563 + 0×2562 + 5×256 + 9.


INET_NTOA(expr)

Given a numeric IPv4 network address in network byte order, returns the dotted-quad representation of the address as a string. INET_NTOA() returns NULL if it does not understand its argument.

As of MySQL 5.5.3, the return value is a nonbinary string in the connection character set. Before 5.5.3, the return value is a binary string.

mysql> SELECT INET_NTOA(167773449);

        -> '10.0.5.9'


In this way you have to use only 4 bytes to store your data, moreover you'll gain CPU time when you will send a query to your database, because comparisons between integers are simplier than comparisons between strings.


The php language provides two functions that do same thing, these functions are described below:

 

ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

int ip2long ( string $ip_address )

The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.

ip2long() will also work with non-complete IP addresses.


long2ip — Converts an (IPv4) Internet network address into a string in Internet standard dotted format

string long2ip ( string $proper_address )

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.

 


You can choose to use MySQL functions or PHP functions depending on your needs, if you want the DB does the work, you should choose the MySQL functions, otherwise you should choose the PHP functions.

Gg1