使用PHP在MySQL数据库中存储IP地址[duplicate]

时间:2023-01-05 22:21:43

This question already has an answer here:

这个问题已经有了答案:

what is the right field type for IP address in mysql? and what is the right way of storing it using PHP?

在mysql中,正确的IP地址字段类型是什么?使用PHP存储它的正确方法是什么?

3 个解决方案

#1


60  

This tutorial might help you.

本教程可能对您有所帮助。

The most efficient way of saving IPv4 addresses is with an INT field (not VARCHAR as you might expect). You convert them using PHP's ip2long and back using either MySQL's INET_NTOA function or PHP's long2ip function.

保存IPv4地址最有效的方法是使用INT字段(而不是VARCHAR)。您可以使用PHP的ip2long进行转换,然后使用MySQL的INET_NTOA函数或PHP的long2ip函数进行转换。

If you need to store IPv6, you'll want to use a BINARY field instead and PHP's inet_pton function.

如果需要存储IPv6,需要使用二进制字段和PHP的inet_pton函数。

#2


47  

you can store them in a binary field with a length of 128 bits (16 bytes, BINARY(16) or VARBINARY(16)). to convert any ip address to its binary representation, you can use the php function inet_pton. this method will work for both IPv4 and IPv6 addresses. inet_ntop can be used to get back the string representation of the stored ip address (regardless of version)

您可以将它们存储在长度为128位(16字节、二进制(16)或VARBINARY(16))的二进制字段中。要将任何ip地址转换为二进制表示,可以使用php函数inet_pton。该方法将同时适用于IPv4和IPv6地址。inet_ntop可以用于获取存储的ip地址的字符串表示形式(不管版本是什么)

#3


14  

Generally you can go with VARCHAR(45) as it will be long enough to even store IPv6.

通常你可以使用VARCHAR(45),因为它足够长,甚至可以存储IPv6。

#1


60  

This tutorial might help you.

本教程可能对您有所帮助。

The most efficient way of saving IPv4 addresses is with an INT field (not VARCHAR as you might expect). You convert them using PHP's ip2long and back using either MySQL's INET_NTOA function or PHP's long2ip function.

保存IPv4地址最有效的方法是使用INT字段(而不是VARCHAR)。您可以使用PHP的ip2long进行转换,然后使用MySQL的INET_NTOA函数或PHP的long2ip函数进行转换。

If you need to store IPv6, you'll want to use a BINARY field instead and PHP's inet_pton function.

如果需要存储IPv6,需要使用二进制字段和PHP的inet_pton函数。

#2


47  

you can store them in a binary field with a length of 128 bits (16 bytes, BINARY(16) or VARBINARY(16)). to convert any ip address to its binary representation, you can use the php function inet_pton. this method will work for both IPv4 and IPv6 addresses. inet_ntop can be used to get back the string representation of the stored ip address (regardless of version)

您可以将它们存储在长度为128位(16字节、二进制(16)或VARBINARY(16))的二进制字段中。要将任何ip地址转换为二进制表示,可以使用php函数inet_pton。该方法将同时适用于IPv4和IPv6地址。inet_ntop可以用于获取存储的ip地址的字符串表示形式(不管版本是什么)

#3


14  

Generally you can go with VARCHAR(45) as it will be long enough to even store IPv6.

通常你可以使用VARCHAR(45),因为它足够长,甚至可以存储IPv6。