ComFreek ComFreek - 2 years ago 222
MySQL Question

Which MySQL datatype to use for an IP address?

Possible Duplicate:

How to store an IP in mySQL

I want to get the IP address from
and some other
variables, which datatype is the right one for this?

Is it

Answer Source

Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:


And INET_ATON and INET_NTOA to convert them:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON(""));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARY instead:

`ipv6` BINARY(16)

And use PHP’s inet_pton and inet_ntop for conversion:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download