1 # Define the main object
6 # Export for both the CommonJS and browser-like environment
7 if module? && module.exports
8 module.exports = ipaddr
10 root['ipaddr'] = ipaddr
12 # A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.
13 matchCIDR = (first, second, partSize, cidrBits) ->
14 if first.length != second.length
15 throw new Error "ipaddr: cannot match CIDR for objects with different lengths"
19 shift = partSize - cidrBits
20 shift = 0 if shift < 0
22 if first[part] >> shift != second[part] >> shift
30 # An utility function to ease named range matching. See examples below.
31 ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') ->
32 for rangeName, rangeSubnets of rangeList
33 # ECMA5 Array.isArray isn't available everywhere
34 if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)
35 rangeSubnets = [ rangeSubnets ]
37 for subnet in rangeSubnets
38 return rangeName if address.match.apply(address, subnet)
42 # An IPv4 address (RFC791).
44 # Constructs a new IPv4 address from an array of four octets
45 # in network order (MSB first)
47 constructor: (octets) ->
49 throw new Error "ipaddr: ipv4 octet count should be 4"
52 if !(0 <= octet <= 255)
53 throw new Error "ipaddr: ipv4 octet should fit in 8 bits"
57 # The 'kind' method exists on both IPv4 and IPv6 classes.
61 # Returns the address in convenient, decimal-dotted format.
63 return @octets.join "."
65 # Returns an array of byte-sized values in network order (MSB first)
67 return @octets.slice(0) # octets.clone
69 # Checks if this address matches other one within given CIDR range.
70 match: (other, cidrRange) ->
71 if cidrRange == undefined
72 [other, cidrRange] = other
74 if other.kind() != 'ipv4'
75 throw new Error "ipaddr: cannot match ipv4 address with non-ipv4 one"
77 return matchCIDR(this.octets, other.octets, 8, cidrRange)
79 # Special IPv4 address ranges.
82 [ new IPv4([0, 0, 0, 0]), 8 ]
85 [ new IPv4([255, 255, 255, 255]), 32 ]
87 multicast: [ # RFC3171
88 [ new IPv4([224, 0, 0, 0]), 4 ]
90 linkLocal: [ # RFC3927
91 [ new IPv4([169, 254, 0, 0]), 16 ]
94 [ new IPv4([127, 0, 0, 0]), 8 ]
97 [ new IPv4([10, 0, 0, 0]), 8 ]
98 [ new IPv4([172, 16, 0, 0]), 12 ]
99 [ new IPv4([192, 168, 0, 0]), 16 ]
101 reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700
102 [ new IPv4([192, 0, 0, 0]), 24 ]
103 [ new IPv4([192, 0, 2, 0]), 24 ]
104 [ new IPv4([192, 88, 99, 0]), 24 ]
105 [ new IPv4([198, 51, 100, 0]), 24 ]
106 [ new IPv4([203, 0, 113, 0]), 24 ]
107 [ new IPv4([240, 0, 0, 0]), 4 ]
110 # Checks if the address corresponds to one of the special ranges.
112 return ipaddr.subnetMatch(this, @SpecialRanges)
114 # Convrets this IPv4 address to an IPv4-mapped IPv6 address.
115 toIPv4MappedAddress: ->
116 return ipaddr.IPv6.parse "::ffff:#{@toString()}"
118 # returns a number of leading ones in IPv4 address, making sure that
119 # the rest is a solid sequence of 0's (valid netmask)
120 # returns either the CIDR length or null if mask is not valid
121 prefixLengthFromSubnetMask: ->
122 # number of zeroes in octet
135 # non-zero encountered stop scanning for zeroes
137 for i in [3..0] by -1
139 if octet of zerotable
140 zeros = zerotable[octet]
141 if stop and zeros != 0
150 # A list of regular expressions that match arbitrary IPv4 addresses,
151 # for which a number of weird notations exist.
152 # Note that an address like 0010.0xa5.1.1 is considered legal.
153 ipv4Part = "(0?\\d+|0x[a-f0-9]+)"
155 fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i'
156 longValue: new RegExp "^#{ipv4Part}$", 'i'
158 # Classful variants (like a.b, where a is an octet, and b is a 24-bit
159 # value representing last three octets; this corresponds to a class C
160 # address) are omitted due to classless nature of modern Internet.
161 ipaddr.IPv4.parser = (string) ->
162 parseIntAuto = (string) ->
163 if string[0] == "0" && string[1] != "x"
168 # parseInt recognizes all that octal & hexadecimal weirdness for us
169 if match = string.match(ipv4Regexes.fourOctet)
170 return (parseIntAuto(part) for part in match[1..5])
171 else if match = string.match(ipv4Regexes.longValue)
172 value = parseIntAuto(match[1])
173 if value > 0xffffffff || value < 0
174 throw new Error "ipaddr: address outside defined range"
175 return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse()
179 # An IPv6 address (RFC2460)
181 # Constructs an IPv6 address from an array of eight 16-bit parts
182 # or sixteen 8-bit parts in network order (MSB first).
183 # Throws an error if the input is invalid.
184 constructor: (parts) ->
185 if parts.length == 16
187 for i in [0..14] by 2
188 @parts.push((parts[i] << 8) | parts[i + 1])
189 else if parts.length == 8
192 throw new Error "ipaddr: ipv6 part count should be 8 or 16"
195 if !(0 <= part <= 0xffff)
196 throw new Error "ipaddr: ipv6 part should fit in 16 bits"
198 # The 'kind' method exists on both IPv4 and IPv6 classes.
202 # Returns the address in compact, human-readable format like
205 stringParts = (part.toString(16) for part in @parts)
207 compactStringParts = []
208 pushPart = (part) -> compactStringParts.push part
211 for part in stringParts
237 return compactStringParts.join ":"
239 # Returns an array of byte-sized values in network order (MSB first)
243 bytes.push(part >> 8)
244 bytes.push(part & 0xff)
248 # Returns the address in expanded format with all zeroes included, like
249 # 2001:db8:8:66:0:0:0:1
250 toNormalizedString: ->
251 return (part.toString(16) for part in @parts).join ":"
253 # Checks if this address matches other one within given CIDR range.
254 match: (other, cidrRange) ->
255 if cidrRange == undefined
256 [other, cidrRange] = other
258 if other.kind() != 'ipv6'
259 throw new Error "ipaddr: cannot match ipv6 address with non-ipv6 one"
261 return matchCIDR(this.parts, other.parts, 16, cidrRange)
263 # Special IPv6 ranges
265 unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after
266 linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ]
267 multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ]
268 loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ]
269 uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ]
270 ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ]
271 rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145
272 rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052
273 '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056
274 teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146
276 [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291
279 # Checks if the address corresponds to one of the special ranges.
281 return ipaddr.subnetMatch(this, @SpecialRanges)
283 # Checks if this address is an IPv4-mapped IPv6 address.
284 isIPv4MappedAddress: ->
285 return @range() == 'ipv4Mapped'
287 # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.
288 # Throws an error otherwise.
290 unless @isIPv4MappedAddress()
291 throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4"
293 [high, low] = @parts[-2..-1]
295 return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff])
297 # IPv6-matching regular expressions.
298 # For IPv6, the task is simpler: it is enough to match the colon-delimited
299 # hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at
301 ipv6Part = "(?:[0-9a-f]+::?)+"
303 native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i'
304 transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" +
305 "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i'
307 # Expand :: in an IPv6 address or address part consisting of `parts` groups.
308 expandIPv6 = (string, parts) ->
309 # More than one '::' means invalid adddress
310 if string.indexOf('::') != string.lastIndexOf('::')
313 # How many parts do we already have?
316 while (lastColon = string.indexOf(':', lastColon + 1)) >= 0
319 # 0::0 is two parts more than ::
320 colonCount-- if string.substr(0, 2) == '::'
321 colonCount-- if string.substr(-2, 2) == '::'
323 # The following loop would hang if colonCount > parts
324 if colonCount > parts
327 # replacement = ':' + '0:' * (parts - colonCount)
328 replacementCount = parts - colonCount
330 while replacementCount--
333 # Insert the missing zeroes
334 string = string.replace('::', replacement)
336 # Trim any garbage which may be hanging around if :: was at the edge in
338 string = string[1..-1] if string[0] == ':'
339 string = string[0..-2] if string[string.length-1] == ':'
341 return (parseInt(part, 16) for part in string.split(":"))
343 # Parse an IPv6 address.
344 ipaddr.IPv6.parser = (string) ->
345 if string.match(ipv6Regexes['native'])
346 return expandIPv6(string, 8)
348 else if match = string.match(ipv6Regexes['transitional'])
349 parts = expandIPv6(match[1][0..-2], 6)
351 octets = [parseInt(match[2]), parseInt(match[3]),
352 parseInt(match[4]), parseInt(match[5])]
354 if !(0 <= octet <= 255)
357 parts.push(octets[0] << 8 | octets[1])
358 parts.push(octets[2] << 8 | octets[3])
363 # Checks if a given string is formatted like IPv4/IPv6 address.
364 ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) ->
365 return @parser(string) != null
367 # Checks if a given string is a valid IPv4/IPv6 address.
368 ipaddr.IPv4.isValid = (string) ->
370 new this(@parser(string))
375 ipaddr.IPv6.isValid = (string) ->
376 # Since IPv6.isValid is always called first, this shortcut
377 # provides a substantial performance gain.
378 if typeof string == "string" and string.indexOf(":") == -1
382 new this(@parser(string))
387 # Tries to parse and validate a string with IPv4/IPv6 address.
388 # Throws an error if it fails.
389 ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) ->
390 parts = @parser(string)
392 throw new Error "ipaddr: string is not formatted like ip address"
394 return new this(parts)
396 ipaddr.IPv4.parseCIDR = (string) ->
397 if match = string.match(/^(.+)\/(\d+)$/)
398 maskLength = parseInt(match[2])
399 if maskLength >= 0 and maskLength <= 32
400 return [@parse(match[1]), maskLength]
402 throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range"
404 ipaddr.IPv6.parseCIDR = (string) ->
405 if match = string.match(/^(.+)\/(\d+)$/)
406 maskLength = parseInt(match[2])
407 if maskLength >= 0 and maskLength <= 128
408 return [@parse(match[1]), maskLength]
410 throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range"
412 # Checks if the address is valid IP address
413 ipaddr.isValid = (string) ->
414 return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string)
416 # Try to parse an address and throw an error if it is impossible
417 ipaddr.parse = (string) ->
418 if ipaddr.IPv6.isValid(string)
419 return ipaddr.IPv6.parse(string)
420 else if ipaddr.IPv4.isValid(string)
421 return ipaddr.IPv4.parse(string)
423 throw new Error "ipaddr: the address has neither IPv6 nor IPv4 format"
425 ipaddr.parseCIDR = (string) ->
427 return ipaddr.IPv6.parseCIDR(string)
430 return ipaddr.IPv4.parseCIDR(string)
432 throw new Error "ipaddr: the address has neither IPv6 nor IPv4 CIDR format"
434 # Try to parse an array in network order (MSB first) for IPv4 and IPv6
435 ipaddr.fromByteArray = (bytes) ->
436 length = bytes.length
438 return new ipaddr.IPv4(bytes)
440 return new ipaddr.IPv6(bytes)
442 throw new Error "ipaddr: the binary input is neither an IPv6 nor IPv4 address"
444 # Parse an address and return plain IPv4 address if it is an IPv4-mapped address
445 ipaddr.process = (string) ->
446 addr = @parse(string)
447 if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress()
448 return addr.toIPv4Address()