1 | 'use strict'
|
2 |
|
3 | const isIp = require('is-ip')
|
4 | const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
|
5 |
|
6 | const isIP = isIp
|
7 | const isV4 = isIp.v4
|
8 | const isV6 = isIp.v6
|
9 |
|
10 |
|
11 |
|
12 | const toBytes = function (ip, buff, offset) {
|
13 | offset = ~~offset
|
14 |
|
15 | let result
|
16 |
|
17 | if (isV4(ip)) {
|
18 | result = buff || new Uint8Array(offset + 4)
|
19 |
|
20 |
|
21 | ip.split(/\./g).map(function (byte) {
|
22 | result[offset++] = parseInt(byte, 10) & 0xff
|
23 | })
|
24 | } else if (isV6(ip)) {
|
25 | const sections = ip.split(':', 8)
|
26 |
|
27 | let i
|
28 | for (i = 0; i < sections.length; i++) {
|
29 | const isv4 = isV4(sections[i])
|
30 | let v4Buffer
|
31 |
|
32 | if (isv4) {
|
33 | v4Buffer = toBytes(sections[i])
|
34 | sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')
|
35 | }
|
36 |
|
37 | if (v4Buffer && ++i < 8) {
|
38 | sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))
|
39 | }
|
40 | }
|
41 |
|
42 | if (sections[0] === '') {
|
43 | while (sections.length < 8) sections.unshift('0')
|
44 | } else if (sections[sections.length - 1] === '') {
|
45 | while (sections.length < 8) sections.push('0')
|
46 | } else if (sections.length < 8) {
|
47 | for (i = 0; i < sections.length && sections[i] !== ''; i++);
|
48 | const argv = [i, '1']
|
49 | for (i = 9 - sections.length; i > 0; i--) {
|
50 | argv.push('0')
|
51 | }
|
52 | sections.splice.apply(sections, argv)
|
53 | }
|
54 |
|
55 | result = buff || new Uint8Array(offset + 16)
|
56 | for (i = 0; i < sections.length; i++) {
|
57 | const word = parseInt(sections[i], 16)
|
58 | result[offset++] = (word >> 8) & 0xff
|
59 | result[offset++] = word & 0xff
|
60 | }
|
61 | }
|
62 |
|
63 | if (!result) {
|
64 | throw Error('Invalid ip address: ' + ip)
|
65 | }
|
66 |
|
67 | return result
|
68 | }
|
69 |
|
70 |
|
71 |
|
72 | const toString = function (buff, offset, length) {
|
73 | offset = ~~offset
|
74 | length = length || (buff.length - offset)
|
75 |
|
76 | const result = []
|
77 | let string
|
78 | const view = new DataView(buff.buffer)
|
79 | if (length === 4) {
|
80 |
|
81 | for (let i = 0; i < length; i++) {
|
82 | result.push(buff[offset + i])
|
83 | }
|
84 | string = result.join('.')
|
85 | } else if (length === 16) {
|
86 |
|
87 | for (let i = 0; i < length; i += 2) {
|
88 | result.push(view.getUint16(offset + i).toString(16))
|
89 | }
|
90 | string = result.join(':')
|
91 | string = string.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')
|
92 | string = string.replace(/:{3,4}/, '::')
|
93 | }
|
94 |
|
95 | return string
|
96 | }
|
97 |
|
98 | module.exports = {
|
99 | isIP,
|
100 | isV4,
|
101 | isV6,
|
102 | toBytes,
|
103 | toString
|
104 | }
|