Comparing IPv4 IP address with Network address stored on MYSQL

Clutch Prince :

I have a large table containing 3 Million network addresses and their location info

basic fields:

network: eg. 74.142.124.116/30,

latitude: eg. 40475, 

longitude: eg. 37.7548

The system also captures the ipv4 address of the user accessing the service (say, 216.255.211.106).

I want to compare this ipv4 and network address and locate the ip address.. Is there a way of doing this in MySQL or node.JS?

Cascader :

You can use the following method:

  • Store the network as startIP and endIP (network & broadcast) in two separate columns in MySQL
  • Find the record containing the address using a simple range query (ip >= startIP and ip <= endIP)

Implementation details:

The optimal datatype for IPv4 address in MySQL is INT UNSIGNED. You can convert your existing data by calculating network and broadcast addresses as (using your example data):

update mytable set startIP = inet_aton('74.142.124.116'), endIP = inet_aton('74.142.124.119')

Assuming your original parameter value (sourceIP) is a dotted decimal formatted IP addres as a string (i.e. '216.255.211.106') you can query the table (you need to add index on (startIP, endIP) as:

select lat, long from mytable where inet_aton(@sourceIP) >= startIP and inet_aton(@sourceIP) <= endIP

(@sourceIP is the parameter value)

Depending on the quality of your data, you might get multiple results (i.e. overlapping network ranges in your dataset)

Update

Credits to Bernd Buffen's answer here

You can use the following statement to populate the two new columns:

update mytable set
startIP = INET_ATON( SUBSTRING_INDEX(cidr, '/', 1)) 
   & 0xffffffff ^ ((0x1 << ( 32 - SUBSTRING_INDEX(cidr, '/', -1))  ) -1 ) 
, endIP = INET_ATON( SUBSTRING_INDEX(cidr, '/', 1)) 
   | ((0x100000000 >> SUBSTRING_INDEX(cidr, '/', -1) ) -1 )

Assuming the original table has a cidr column.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379311&siteId=1