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.

69 lines
1.4 KiB

1 month ago
  1. # @leichtgewicht/ip-codec
  2. Small package to encode or decode IP addresses from buffers to strings.
  3. Supports IPV4 and IPV6.
  4. ## Usage
  5. The basics are straigthforward
  6. ```js
  7. import { encode, decode, sizeOf, familyOf } from '@leichtgewicht/ip-codec'
  8. const uint8Array = encode("127.0.0.1")
  9. const str = decode(uint8Array)
  10. try {
  11. switch sizeOf(str) {
  12. case 4: // IPv4
  13. case 16: // IPv6
  14. }
  15. switch familyOf(str) {
  16. case: 1: // IPv4
  17. case: 2: // IPv6
  18. }
  19. } catch (err) {
  20. // Invalid IP
  21. }
  22. ```
  23. By default the library will work with Uint8Array's but you can bring your own buffer:
  24. ```js
  25. const buf = Buffer.alloc(4)
  26. encode('127.0.0.1', buf)
  27. ```
  28. It is also possible to de-encode at a location inside a given buffer
  29. ```js
  30. const buf = Buffer.alloc(10)
  31. encode('127.0.0.1', buf, 4)
  32. ```
  33. Allocation of a buffer may be difficult if you don't know what type the buffer:
  34. you can pass in a generator to allocate it for you:
  35. ```js
  36. encode('127.0.0.1', Buffer.alloc)
  37. ```
  38. You can also de/encode ipv4 or ipv6 specifically:
  39. ```js
  40. import { v4, v6 } from '@leichtgewicht/ip-codec'
  41. v4.decode(v4.encode('127.0.0.1'))
  42. v6.decode(v6.encode('::'))
  43. ```
  44. ## History
  45. The code in this package was originally extracted from [node-ip](https://github.com/indutny/node-ip) and since improved.
  46. Notable changes are the removal of the `Buffer` dependency and better support for detection of
  47. formats and allocation of buffers.
  48. ## License
  49. [MIT](./LICENSE)