Best way to store an ip in mysql
I used to use varchar(15).
But a little poking around yielded a better solution.
Turns out there’s a standard set of MySQL functions for translating an IP address to and from an integer.
ALTER TABLE `sessions` ADD `client_ip` INT NOT NULL AFTER `created_at`; mysql> SELECT INET_ATON('192.168.10.50') AS ipn; +------------+ | ipn | +------------+ | 3232238130 | +------------+ mysql> SELECT INET_NTOA(3232238130) AS ipa; +--------------+ | ipa | +--------------+ | 192.168.10.50 | +--------------+
Here’s the algo in case you’re curious:
(192 * 2^24) + (168 * 2^16) + (10 * 2^8) + 50 = 3232238130
Comments(0)