Comparison

util/ip.lua @ 8437:021129f7b0a3

util.ip: Do CIDR matching by comparing all bits at once instead of using O(n) function
author Kim Alvefur <zash@zash.se>
date Fri, 01 Dec 2017 03:29:25 +0100
parent 8436:ab9ddfb03d4d
child 8438:499663bd0122
comparison
equal deleted inserted replaced
8436:ab9ddfb03d4d 8437:021129f7b0a3
226 end 226 end
227 return new_ip(cidr), bits; 227 return new_ip(cidr), bits;
228 end 228 end
229 229
230 function match(ipA, ipB, bits) 230 function match(ipA, ipB, bits)
231 local common_bits = commonPrefixLength(ipA, ipB); 231 if not bits then
232 if bits and ipB.proto == "IPv4" then 232 return ipA == ipB;
233 common_bits = common_bits - 96; -- v6 mapped addresses always share these bits 233 elseif bits < 1 then
234 end 234 return true;
235 return common_bits >= (bits or 128); 235 end
236 if ipA.proto ~= ipB.proto then
237 if ipA.proto == "IPv4" then
238 ipA = ipA.toV4mapped;
239 elseif ipB.proto == "IPv4" then
240 ipB = ipA.toV4mapped;
241 bits = bits + (128 - 32);
242 end
243 end
244 return ipA.bits:sub(1, bits) == ipB.bits:sub(1, bits);
236 end 245 end
237 246
238 return { 247 return {
239 new_ip = new_ip, 248 new_ip = new_ip,
240 commonPrefixLength = commonPrefixLength, 249 commonPrefixLength = commonPrefixLength,