将 IP 地址与 IP 范围匹配?

发布于 2024-08-30 06:14:25 字数 803 浏览 8 评论 0原文

我有一个 MySQL 表设置如下:

+---------------+-------------+------+-----+---------+----------------+
| Field         | Type        | Null | Key | Default | Extra          |
+---------------+-------------+------+-----+---------+----------------+
| ipaddress_s   | varchar(15) | YES  | MUL | NULL    |                | 
| ipaddress_e   | varchar(16) | YES  |     | NULL    |                | 
+---------------+-------------+------+-----+---------+----------------+

其中,ipaddress_s 和 ipaddress_e 看起来像: 4.100.159.0-4.100.159.255

现在有没有一种方法可以真正获取包含给定 IP 地址的行?例如,给定 IP 地址:“4.100.159.5”,我希望返回上面的行。所以我正在尝试一个看起来像这样的查询(但这当然是错误的,因为在下面我将 IP 视为字符串):

SELECT * FROM ranges WHERE ipaddress_s<"4.100.159.5" AND ipaddress_e>"4.100.159.5"

有什么建议吗?

I have a MySQL table setup as follows:

+---------------+-------------+------+-----+---------+----------------+
| Field         | Type        | Null | Key | Default | Extra          |
+---------------+-------------+------+-----+---------+----------------+
| ipaddress_s   | varchar(15) | YES  | MUL | NULL    |                | 
| ipaddress_e   | varchar(16) | YES  |     | NULL    |                | 
+---------------+-------------+------+-----+---------+----------------+

where, ipaddress_s and ipaddress_e look something like: 4.100.159.0-4.100.159.255

Now is there a way I can actually get the row that contains a given IP address? For instance, given the IP address: "4.100.159.5", I want the above row to be returned. So I am trying for a query that looks something like this (but of course this is wrong because in the following I am considering IPs as strings):

SELECT * FROM ranges WHERE ipaddress_s<"4.100.159.5" AND ipaddress_e>"4.100.159.5"

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无畏 2024-09-06 06:14:25

INET_ATON(expr) 会将 IP 地址字符串更改为可用于比较的数字地址。

http://dev.mysql.com/doc /refman/5.0/en/miscellaneous-functions.html#function_inet-aton

SELECT * FROM ranges WHERE INET_ATON(ipaddress_s)<INET_ATON('4.100.159.0') AND INET_ATON(ipaddress_e)>INET_ATON('4.100.159.5')

INET_ATON(expr) will change an ip address string into a numeric address that you can use for comparison.

http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton

SELECT * FROM ranges WHERE INET_ATON(ipaddress_s)<INET_ATON('4.100.159.0') AND INET_ATON(ipaddress_e)>INET_ATON('4.100.159.5')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文