Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ip address compare in database

Tags:

php

mysql

I am trying to solve a problem that could compare 2 columns in a table. the table is as follows

------------------------------------------
|  from    |    to           |  Country  |
------------------------------------------
| 25.0.0.1 | 25.255.255.255  |  denmark  |
------------------------------------------
| 68.0.0.1 | 68.255.255.255  |  USA      |

My problem is i have a ip of 25.195.32.0 and i want to compare this to the from and to column and return the country name.

like image 863
likith sai Avatar asked May 05 '14 06:05

likith sai


People also ask

How do I compare two IP addresses?

The easiest way to determine the range is to convert the IP into a decimal format and then do the ordinary comparing statements necessary. You can do this by assigning a weight for each part of the IP. Each part has a maximum value of 255. Thus, the best weight you can choose is 256.

Can I store IP address in database?

We can store an IP address with the help of INT unsigned. While using INSERT, include INET_ATON() and with SELECT, include INET_NTOA(). IP address is in dotted format.

What data type is IP address in SQL?

As with MS SQL Server you can store IP address, both IPv4 and IPv6, either as varchar or as numeric.


1 Answers

You can use INET_ATON to get a numeric value of the IPs to compare.

SELECT country FROM table
WHERE INET_ATON('25.195.32.0') BETWEEN INET_ATON(from) AND INET_ATON(to)

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

like image 151
Mark Miller Avatar answered Oct 01 '22 12:10

Mark Miller