MYSQL - 选择 IP v4/v6、inet_pton & bin2hex
我在从 mysql sql 服务器中选择正确的值时遇到了一些麻烦。
IP 可以是 ipv6 和 v4。
表: User{
...
ip binary(16)
}
$ip = '192.168.10.115';
$ip = bin2hex(inet_pton($ip)); // Returns c0a80a73
$result = $this->db->select("SELECT * FROM User WHERE HEX(ip) = $ip");
// $result empty because in db its stored as:
// HEX(ip) = C0A80A73000000000000000000000000
如何获得与 * 00000 * 的可行匹配?
如果输入是 ipv6 匹配,则可以,但 ip v4 则不行。
I'm having bit of a trouble selecting correct values from my mysql sql server.
The ip can be ipv6 and v4.
Table: User{
...
ip binary(16)
}
$ip = '192.168.10.115';
$ip = bin2hex(inet_pton($ip)); // Returns c0a80a73
$result = $this->db->select("SELECT * FROM User WHERE HEX(ip) = $ip");
// $result empty because in db its stored as:
// HEX(ip) = C0A80A73000000000000000000000000
How can I get a viable match to the * 00000 * ?
If input was a ipv6 match this would be ok, but ip v4 not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
VARBINARY
而不仅仅是BINARY
吗?来自 Binary/Varbinary 上的 MySQL 手册:
Can you use
VARBINARY
instead of justBINARY
?From the MySQL Manual on Binary/Varbinary:
更新:
MySQL 5.6.3 及更高版本支持 IPv6 地址 - 请参阅以下内容:“INET6_ATON(expr)”
数据类型为
VARBINARY(16)
而不是 < code>BINARY(16) 正如之前的评论所建议的。唯一的原因是 MySQL 函数同时适用于 IPv6 和 IPv4 地址。BINARY(16)
适合仅存储 IPv6 地址并节省 1 个字节。处理 IPv6 和 IPv4 地址时应使用VARBINARY(16)
。UPDATE:
The MySQL 5.6.3 and higher have support for IPv6 addresses - see the following: "INET6_ATON(expr)"
The data type is
VARBINARY(16)
instead ofBINARY(16)
as was suggested by earlier comments here. The only reason for this is that the MySQL functions work for both IPv6 and IPv4 addresses.BINARY(16)
is fine for storing only IPv6 addresses and saves one byte.VARBINARY(16)
should be used when handling both IPv6 and IPv4 addresses.