匹配IP地址和IP范围? [英] Matching an IP address with an IP range?
问题描述
我有一个MySQL表设置如下:
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 | |
+---------------+-------------+------+-----+---------+----------------+
其中,ipaddress_s和ipaddress_e类似于:4.100.159.0-4.100.159.255
where, ipaddress_s and ipaddress_e look something like: 4.100.159.0-4.100.159.255
现在有一种方法可以实际获得包含给定的行IP地址?例如,给定IP地址:4.100.159.5,我希望返回上面的行。所以我正在尝试看起来像这样的查询(但当然这是错误的,因为在下面我将IP视为字符串):
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"
有什么建议吗?
推荐答案
INET_ATON(expr)会将ip地址字符串更改为可以使用的数字地址用于比较。
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')
这篇关于匹配IP地址和IP范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!