How to save IP address (v4 or v6) as int in any database using php?

I need to save the IP address in the most compact way, the search is not a concern. It should also be compatible with Windows, Linux and Mac using any DB (MySQL, SQLite, Postgres, etc.).

Thanks to ip2long () and the long2ip () function in PHP, I can convert the IP4 address to a small int field, not varchar (15) or whatever. The problem is that we are in the transition phase to IP6, which means that most existing best practices do not work, including features that do not work with IP6. Moreover, DB functions such as INET_ATON () and INET_NTOA () are not parameters here.

So, how do you store the IP address as INT (or any other compact format) in a way that will work on any system?

EDIT: In a stream, the Wrang-wrang pointer indicates the use of inet_ntop () and inet_ptop () for packing and unpacking IP4 or IP6. The problem is that they only work with Linux / Mac with PHP +5.1 (this is not a big problem) and on windows with +5.3 (which is).

If this is not a problem, is it their replacement for the varbinary (16) field, which was recommended in each database?

+4
source share
2 answers

You just need to choose a 128 bit storage method:

:: / 96 - This is a 96-bit null prefix, originally known as IPv4-compatible addresses. This class of addresses was used to represent IPv4 addresses in IPv6 transition technology. Such an IPv6 address has the first 96 bits, but while the last 32 bits are the IPv4 address that is represented. The Internet Engineering Task Force (IETF) did not recommend the use of IPv4-compliant addresses as published in RFC 4291. The only remaining use of this address format is to present the IPv4 address to a table or database with a fixed member size, which should also be able to save the IPv6 address .

(from http://en.wikipedia.org/wiki/IPv6 )

I think two BIGINT UNSIGNEDs would be a reasonable way to store them, but I think you could use binary (an array of bytes).

This question, it seems, has already been given in Working with IPv6 Addresses in PHP and How to Store an IPv6 Compatible Address in a Relational Database

+4
source

You can use this universal php library : its ip2long and long2ip work with both IPv4 and IPv6.

0
source

All Articles