Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to store IP Address in MySQL [duplicate]

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?

like image 357
ensnare Avatar asked Mar 29 '10 23:03

ensnare


People also ask

How to store IPV4 in MySQL?

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.

What is data type for IP address in MySQL?

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.

How can I get IP address and store in database using PHP?

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.

What is the data type of 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.


2 Answers

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) 
like image 177
Daniel Vassallo Avatar answered Oct 01 '22 09:10

Daniel Vassallo


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")

like image 41
Dean Harding Avatar answered Oct 01 '22 08:10

Dean Harding