简体   繁体   中英

Mysql compare ip address

I have a database which stores IP address with its location. I only store the first 3 network ID of IP address in the table.

+-------------------+-----------------+
|ip_address(varchar)|location(varchar)|
+-------------------+-----------------+
| 1.2.3             |       A         |
| 1.2.4             |       A         |
| 1.22.33           |       B         |
| 1.100.99          |       C         |
+-------------------+-----------------+

Let say my IP is 1.2.3.4 or others 1.100.99.20, how do I compare the IP with the table to get the location?

Here's a solution that should work and be indexable too:

SELECT location
FROM WhateverTable
WHERE ip_address = SUBSTRING_INDEX(?, '.', 3)

Where you supply the value '1.100.99.20' for the ? parameter.


You should be aware that the IP addresses you store are misleading. The official IP address format permits shortened strings, but not the way you probably think. For example:

mysql> select inet_ntoa(inet_aton('1.100.99'));
+----------------------------------+
| inet_ntoa(inet_aton('1.100.99')) |
+----------------------------------+
| 1.100.0.99                       |
+----------------------------------+

I bet you would expect it to return 1.100.99.0.

SELECT location
FROM address_table
WHERE AND INET_ATON(@my_address) BETWEEN INET_ATON(CONCAT(ip_address, '.0'))
                                     AND INET_ATON(CONCAT(ip_address, '.255'))

Of course this query cannot use the index even if it exists...


I recommend you do NOT trim the ip_address column value. And the best way is to store not trimmed subnet address but IP addresses range (from - till) in two columns in numeric form - this protects against typos (and decreases rows amount). You may use generated columns with string representation of IP addresses ranges if needed.

This is not the most pragmatic approach, but it does the work.

We could use the LOCATE() function, which takes two arguments representing the substring that you're looking for and the string in which to look for it. (locate function reference: https://www.oreilly.com/library/view/mysql-cookbook/0596001452/ch04s06.html )

The first argument that is going to be passed is the column ip_address and the second argument will be your IP (eg: 1.2.3.4).

SELECT location
FROM that_table
WHERE LOCATE(ip_address, 'the_ip') >= 1;

If we get the number greater or equal than one, it means that it found a match, therefore that ip is going to have a location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM