Search code examples
phpmysqlip-addressipv6ipv4

Storing and retrieving IPv4 and IPv6 addresses


There's a million questions on SO about the best way to store IPv4 and IPv6 addresses on a PHP/MySQL setup, but the answers are either out of date (only IPv4) or they're contradictory/incomplete.

I've created this question to go with a clear answer that gives you everything you need to know.


Solution

  • When you only had to worry about IPv4, you could use PHP's ip2long and long2ip to quickly and easily convert an IP address to a integer. These days, however, nearly everyone should expect to come across some IPv6 addresses at some point, and that's something that's only going to increase.

    A common and efficient solution to have both is to use PHP's inet_pton function (which handles both IPv4 and v6), and then store the result in a VARBINARY(16) column in your database.

    So, let's say we have an IPv6 address like: FE80:0000:0000:0000:0202:B3FF:FE1E:8329

    When converted with inet_pton and stored in a VARBINARY(16) column it looks like this:

    0xfe800000000000000202b3fffe1e8329

    You can then retrieve this from your database and display it using inet_ntop.

    Eg:

    echo inet_ntop($ipAddressFromDB);
    

    This is a quick and efficient way to store IP addresses in an MySQL database.