From 62a1d8a2d312c61673f868878efdcb747c63f772 Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Sat, 18 May 2013 16:45:29 +0100 Subject: util.ip: Add CIDR notation parsing and matching --- util/ip.lua | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) (limited to 'util') diff --git a/util/ip.lua b/util/ip.lua index 20ea3dd7..8cf0076e 100644 --- a/util/ip.lua +++ b/util/ip.lua @@ -215,5 +215,28 @@ function ip_methods:private() return private; end +local function parse_cidr(cidr) + local bits; + local ip_len = cidr:find("/", 1, true); + if ip_len then + bits = tonumber(cidr:sub(ip_len+1, -1)); + cidr = cidr:sub(1, ip_len-1); + end + return new_ip(cidr), bits; +end + +local function match(ipA, ipB, bits) + local common_bits = commonPrefixLength(ipA, ipB); + if not bits then + return ipA == ipB; + end + if bits and ipB.proto == "IPv4" then + common_bits = common_bits - 96; -- v6 mapped addresses always share these bits + end + return common_bits >= bits; +end + return {new_ip = new_ip, - commonPrefixLength = commonPrefixLength}; + commonPrefixLength = commonPrefixLength, + parse_cidr = parse_cidr, + match=match}; -- cgit v1.2.3