What is the most efficient way to store and retrieve IP addresses in MySQL? Right now I'm doing:
SELECT * FROM logins WHERE ip = '1.2.3.4'
Where ip is a VARCHAR(15)
field.
Is there a better way to do this?
We can store an IP address with the help of INT unsigned. While using INSERT, include INET_ATON() and with SELECT, include INET_NTOA(). IP address is in dotted format.
MySQL. While MySQL doesn't have a data type for IP addresses, it's still easy to compare IPs in MySQL. Using inet_aton you can convert your IP addresses to integers before you compare.
You can try this one also. $ip=$_SERVER['REMOTE_ADDR']; echo "IP address= $ip"; If your application hosted on same machine from where you are trying to request it will always return '::1', It means LocalHost. else it will return client IP Address.
IP Network Address Data Types. IPV4 and IPV6 are abstract data types that store IPv4 and IPv6 host addresses, respectively, in binary format. IPV4 is a 4-byte host address in dotted-decimal notation (four decimal numbers, each ranging from 0 to 255, separated by dots). For example: 172.16.
For IPv4 addresses, you may want to store them as an int unsigned
and use the INET_ATON()
and INET_NTOA()
functions to return the IP address from its numeric value, and vice versa.
Example:
SELECT INET_ATON('127.0.0.1'); +------------------------+ | INET_ATON('127.0.0.1') | +------------------------+ | 2130706433 | +------------------------+ 1 row in set (0.00 sec) SELECT INET_NTOA('2130706433'); +-------------------------+ | INET_NTOA('2130706433') | +-------------------------+ | 127.0.0.1 | +-------------------------+ 1 row in set (0.02 sec)
If you only want to store IPv4 addresses, then you can store them in a 32-bit integer field.
If you want to support IPv6 as well, then a string is probably the most easy-to-read/use way (though you could technically store them in a 16-byte VARBINARY()
field, it would be annoying trying to generate SQL statements to select by IP address "by hand")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With