What is the proper way to convert ip to integer in php?
So I need to store IP addresses in database, but storing them as stings is not very efficient and not very convenient for my purpose.开发者_运维技巧
So... How can I convert ip into integer in php with as less processing as possible because it will be done millions of times a day.
And of course how can I convert back from integet to ip?
I know this can be googled and there's some easy solutions - but I'm asking for the fastest way, not just for "do X and you get Y" because it's actually pretty easy task.
Use ip2long()
and long2ip()
. They are the fastest you can find in PHP, because they are just built on top of the corresponding C functions.
Use ip2long
-- this function is so fast, it simply doesn't matter if you call it a million times a day. It is a library function, it is thus well-tested and reliable.
And, considering your working time, it is definitely the fastest solution in the whole universe.
You can use an INT
$ip = ip2long($ip);
To save in mysql:
$sql = "INSERT INTO user(ip) VALUES('$ip')";
$dbQuery = mysql_query($sql,$dbLink
You can get back the ip later :
SELECT INET_NTOA(ip) FROM 'user' WHERE 1
INET_NTOA(expr):
Given a numeric IPv4 network address in network byte order, returns the dotted-quad representation of the address as a binary string. INET_NTOA() returns NULL if it does not understand its argument.
mysql> SELECT INET_NTOA(167773449); -> '10.0.5.9'
Others have correctly pointed you to the ip2long()
function. However, the question and answers are now around 10 years old. Back then, IPv6 was not widely used, but nowadays, it is, and its use is increasing.
If passed an IPv6 address, ip2long
will return false
, which, depending on the logic of your code, may get typecast to 0, which corresponds to the IP address 0.0.0.0.
In theory you could convert IPv6 addresses to 128-bit integers. Unfortunately, on 64-bit systems, 128-bit integers are a bit difficult to work with. The following question may be useful:
Php convert ipv6 to number
As for storing them in a database, the following question addresses it for MySQL:
Storing IPv6 Addresses in MySQL
Based on what I see in these answers and others to similar questions, I'm not sure if there is yet a consensus around a best method for these, the way there is for ip2long/long2ip for IPv4 addresses.
精彩评论