Monday, April 4, 2011

How to store IP address value in integer datatype column.

Most of the time, we use string datatype column like char or varchar to store ip address values. There is a way to store ip address value in numeric datatype column like unsigned interger. There is miscellaneous functions INET_ATON(), INET_NTOA() using which it's possible

INET_ATON() Return the numeric value of an IP address
INET_NTOA() Return the IP address from a numeric value

SELECT INET_ATON('192.168.1.5') AS IP;
+------------+
| IP |
+------------+
| 3232235781 |
+------------+
1 row in set (0.00 sec)
The generated number is always in network byte order. For example
192x256^3 + 168x256^2 + 1x256^1 + 5
SELECT INET_NTOA('3232235781') AS IP;
+-------------+
| IP |
+-------------+
| 192.168.1.5 |
+-------------+
1 row in set (0.00 sec)