Software / code / prosody
Comparison
util/ip.lua @ 5603:e07f4f02e4f9
util.ip: Add CIDR notation parsing and matching
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Sat, 18 May 2013 16:45:29 +0100 |
| parent | 5599:34e9f237b915 |
| child | 5608:0200945313c9 |
comparison
equal
deleted
inserted
replaced
| 5602:e8a0e545ee05 | 5603:e07f4f02e4f9 |
|---|---|
| 213 end | 213 end |
| 214 self.private = private; | 214 self.private = private; |
| 215 return private; | 215 return private; |
| 216 end | 216 end |
| 217 | 217 |
| 218 local function parse_cidr(cidr) | |
| 219 local bits; | |
| 220 local ip_len = cidr:find("/", 1, true); | |
| 221 if ip_len then | |
| 222 bits = tonumber(cidr:sub(ip_len+1, -1)); | |
| 223 cidr = cidr:sub(1, ip_len-1); | |
| 224 end | |
| 225 return new_ip(cidr), bits; | |
| 226 end | |
| 227 | |
| 228 local function match(ipA, ipB, bits) | |
| 229 local common_bits = commonPrefixLength(ipA, ipB); | |
| 230 if not bits then | |
| 231 return ipA == ipB; | |
| 232 end | |
| 233 if bits and ipB.proto == "IPv4" then | |
| 234 common_bits = common_bits - 96; -- v6 mapped addresses always share these bits | |
| 235 end | |
| 236 return common_bits >= bits; | |
| 237 end | |
| 238 | |
| 218 return {new_ip = new_ip, | 239 return {new_ip = new_ip, |
| 219 commonPrefixLength = commonPrefixLength}; | 240 commonPrefixLength = commonPrefixLength, |
| 241 parse_cidr = parse_cidr, | |
| 242 match=match}; |