|
Last change
on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago |
|
Fix frontend appearance
|
-
Property mode
set to
100644
|
|
File size:
1.4 KB
|
| Line | |
|---|
| 1 | # @leichtgewicht/ip-codec
|
|---|
| 2 |
|
|---|
| 3 | Small package to encode or decode IP addresses from buffers to strings.
|
|---|
| 4 | Supports IPV4 and IPV6.
|
|---|
| 5 |
|
|---|
| 6 | ## Usage
|
|---|
| 7 |
|
|---|
| 8 | The basics are straigthforward
|
|---|
| 9 |
|
|---|
| 10 | ```js
|
|---|
| 11 | import { encode, decode, sizeOf, familyOf } from '@leichtgewicht/ip-codec'
|
|---|
| 12 |
|
|---|
| 13 | const uint8Array = encode("127.0.0.1")
|
|---|
| 14 | const str = decode(uint8Array)
|
|---|
| 15 |
|
|---|
| 16 | try {
|
|---|
| 17 | switch sizeOf(str) {
|
|---|
| 18 | case 4: // IPv4
|
|---|
| 19 | case 16: // IPv6
|
|---|
| 20 | }
|
|---|
| 21 | switch familyOf(str) {
|
|---|
| 22 | case: 1: // IPv4
|
|---|
| 23 | case: 2: // IPv6
|
|---|
| 24 | }
|
|---|
| 25 | } catch (err) {
|
|---|
| 26 | // Invalid IP
|
|---|
| 27 | }
|
|---|
| 28 | ```
|
|---|
| 29 |
|
|---|
| 30 | By default the library will work with Uint8Array's but you can bring your own buffer:
|
|---|
| 31 |
|
|---|
| 32 | ```js
|
|---|
| 33 | const buf = Buffer.alloc(4)
|
|---|
| 34 | encode('127.0.0.1', buf)
|
|---|
| 35 | ```
|
|---|
| 36 |
|
|---|
| 37 | It is also possible to de-encode at a location inside a given buffer
|
|---|
| 38 |
|
|---|
| 39 | ```js
|
|---|
| 40 | const buf = Buffer.alloc(10)
|
|---|
| 41 | encode('127.0.0.1', buf, 4)
|
|---|
| 42 | ```
|
|---|
| 43 |
|
|---|
| 44 | Allocation of a buffer may be difficult if you don't know what type the buffer:
|
|---|
| 45 | you can pass in a generator to allocate it for you:
|
|---|
| 46 |
|
|---|
| 47 | ```js
|
|---|
| 48 | encode('127.0.0.1', Buffer.alloc)
|
|---|
| 49 | ```
|
|---|
| 50 |
|
|---|
| 51 | You can also de/encode ipv4 or ipv6 specifically:
|
|---|
| 52 |
|
|---|
| 53 | ```js
|
|---|
| 54 | import { v4, v6 } from '@leichtgewicht/ip-codec'
|
|---|
| 55 |
|
|---|
| 56 | v4.decode(v4.encode('127.0.0.1'))
|
|---|
| 57 | v6.decode(v6.encode('::'))
|
|---|
| 58 | ```
|
|---|
| 59 |
|
|---|
| 60 | ## History
|
|---|
| 61 |
|
|---|
| 62 | The code in this package was originally extracted from [node-ip](https://github.com/indutny/node-ip) and since improved.
|
|---|
| 63 |
|
|---|
| 64 | Notable changes are the removal of the `Buffer` dependency and better support for detection of
|
|---|
| 65 | formats and allocation of buffers.
|
|---|
| 66 |
|
|---|
| 67 | ## License
|
|---|
| 68 |
|
|---|
| 69 | [MIT](./LICENSE)
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.