You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

233 lines
8.1 KiB

  1. # ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js)
  2. ipaddr.js is a small (1.9K minified and gzipped) library for manipulating
  3. IP addresses in JavaScript environments. It runs on both CommonJS runtimes
  4. (e.g. [nodejs]) and in a web browser.
  5. ipaddr.js allows you to verify and parse string representation of an IP
  6. address, match it against a CIDR range or range list, determine if it falls
  7. into some reserved ranges (examples include loopback and private ranges),
  8. and convert between IPv4 and IPv4-mapped IPv6 addresses.
  9. [nodejs]: http://nodejs.org
  10. ## Installation
  11. `npm install ipaddr.js`
  12. or
  13. `bower install ipaddr.js`
  14. ## API
  15. ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS,
  16. it is exported from the module:
  17. ```js
  18. var ipaddr = require('ipaddr.js');
  19. ```
  20. The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4.
  21. ### Global methods
  22. There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and
  23. `ipaddr.process`. All of them receive a string as a single parameter.
  24. The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or
  25. IPv6 address, and `false` otherwise. It does not throw any exceptions.
  26. The `ipaddr.parse` method returns an object representing the IP address,
  27. or throws an `Error` if the passed string is not a valid representation of an
  28. IP address.
  29. The `ipaddr.process` method works just like the `ipaddr.parse` one, but it
  30. automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts
  31. before returning. It is useful when you have a Node.js instance listening
  32. on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its
  33. equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4
  34. connections on your IPv6-only socket, but the remote address will be mangled.
  35. Use `ipaddr.process` method to automatically demangle it.
  36. ### Object representation
  37. Parsing methods return an object which descends from `ipaddr.IPv6` or
  38. `ipaddr.IPv4`. These objects share some properties, but most of them differ.
  39. #### Shared properties
  40. One can determine the type of address by calling `addr.kind()`. It will return
  41. either `"ipv6"` or `"ipv4"`.
  42. An address can be converted back to its string representation with `addr.toString()`.
  43. Note that this method:
  44. * does not return the original string used to create the object (in fact, there is
  45. no way of getting that string)
  46. * returns a compact representation (when it is applicable)
  47. A `match(range, bits)` method can be used to check if the address falls into a
  48. certain CIDR range.
  49. Note that an address can be (obviously) matched only against an address of the same type.
  50. For example:
  51. ```js
  52. var addr = ipaddr.parse("2001:db8:1234::1");
  53. var range = ipaddr.parse("2001:db8::");
  54. addr.match(range, 32); // => true
  55. ```
  56. Alternatively, `match` can also be called as `match([range, bits])`. In this way,
  57. it can be used together with the `parseCIDR(string)` method, which parses an IP
  58. address together with a CIDR range.
  59. For example:
  60. ```js
  61. var addr = ipaddr.parse("2001:db8:1234::1");
  62. addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true
  63. ```
  64. A `range()` method returns one of predefined names for several special ranges defined
  65. by IP protocols. The exact names (and their respective CIDR ranges) can be looked up
  66. in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"`
  67. (the default one) and `"reserved"`.
  68. You can match against your own range list by using
  69. `ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example:
  70. ```js
  71. var rangeList = {
  72. documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ],
  73. tunnelProviders: [
  74. [ ipaddr.parse('2001:470::'), 32 ], // he.net
  75. [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6
  76. ]
  77. };
  78. ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders"
  79. ```
  80. The addresses can be converted to their byte representation with `toByteArray()`.
  81. (Actually, JavaScript mostly does not know about byte buffers. They are emulated with
  82. arrays of numbers, each in range of 0..255.)
  83. ```js
  84. var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com
  85. bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, <zeroes...>, 0x00, 0x68 ]
  86. ```
  87. The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them
  88. have the same interface for both protocols, and are similar to global methods.
  89. `ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address
  90. for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser.
  91. `ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format.
  92. [IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186
  93. [IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71
  94. #### IPv6 properties
  95. Sometimes you will want to convert IPv6 not to a compact string representation (with
  96. the `::` substitution); the `toNormalizedString()` method will return an address where
  97. all zeroes are explicit.
  98. For example:
  99. ```js
  100. var addr = ipaddr.parse("2001:0db8::0001");
  101. addr.toString(); // => "2001:db8::1"
  102. addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1"
  103. ```
  104. The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped
  105. one, and `toIPv4Address()` will return an IPv4 object address.
  106. To access the underlying binary representation of the address, use `addr.parts`.
  107. ```js
  108. var addr = ipaddr.parse("2001:db8:10::1234:DEAD");
  109. addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead]
  110. ```
  111. A IPv6 zone index can be accessed via `addr.zoneId`:
  112. ```js
  113. var addr = ipaddr.parse("2001:db8::%eth0");
  114. addr.zoneId // => 'eth0'
  115. ```
  116. #### IPv4 properties
  117. `toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address.
  118. To access the underlying representation of the address, use `addr.octets`.
  119. ```js
  120. var addr = ipaddr.parse("192.168.1.1");
  121. addr.octets // => [192, 168, 1, 1]
  122. ```
  123. `prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or
  124. null if the netmask is not valid.
  125. ```js
  126. ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28
  127. ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null
  128. ```
  129. `subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length.
  130. ```js
  131. ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0"
  132. ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248"
  133. ```
  134. `broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation.
  135. ```js
  136. ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255"
  137. ```
  138. `networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation.
  139. ```js
  140. ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0"
  141. ```
  142. #### Conversion
  143. IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays.
  144. The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object
  145. if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values,
  146. while for IPv6 it has to be an array of sixteen 8-bit values.
  147. For example:
  148. ```js
  149. var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]);
  150. addr.toString(); // => "127.0.0.1"
  151. ```
  152. or
  153. ```js
  154. var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
  155. addr.toString(); // => "2001:db8::1"
  156. ```
  157. Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB).
  158. For example:
  159. ```js
  160. var addr = ipaddr.parse("127.0.0.1");
  161. addr.toByteArray(); // => [0x7f, 0, 0, 1]
  162. ```
  163. or
  164. ```js
  165. var addr = ipaddr.parse("2001:db8::1");
  166. addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
  167. ```