Possible Duplicate:
How to store an IP in mySQL
I want to get the IP address from $_SERVER['REMOTE_ADDR']
and some other $_SERVER
variables, which datatype is the right one for this?
Is it VARCHAR(n)
?
Possible Duplicate:
How to store an IP in mySQL
I want to get the IP address from $_SERVER['REMOTE_ADDR']
and some other $_SERVER
variables, which datatype is the right one for this?
Is it VARCHAR(n)
?
For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs
INT(11) UNSIGNED
. You can use MySQL'sINET_ATON()
function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, likeBETWEEN
queriesINET_ATON() MySQL function
Since IPv4 addresses are 4 byte long, you could use an
INT
(UNSIGNED
) that has exactly 4 bytes:And
INET_ATON
andINET_NTOA
to convert them:For IPv6 addresses you could use a
BINARY
instead:And use PHP’s
inet_pton
andinet_ntop
for conversion:You have two possibilities (for an IPv4 address) :
varchar(15)
, if your want to store the IP address as a string192.128.0.15
for instanceinteger
(4 bytes), if you convert the IP address to an integer3229614095
for the IP I used beforeThe second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).
About those manipulations, see the
ip2long()
andlong2ip()
functions, on the PHP-side, orinet_aton()
andinet_ntoa()
on the MySQL-side.