forked from mafintosh/dns-packet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathip.js
94 lines (78 loc) · 2.31 KB
/
ip.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict'
var ip = exports;
var ipv4Regex = /^(\d{1,3}\.){3,3}\d{1,3}$/;
var ipv6Regex =
/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;
function isV4Format (ip) {
return ipv4Regex.test(ip);
};
function isV6Format (ip) {
return ipv6Regex.test(ip);
};
ip.toString = function (buff, offset, length) {
offset = ~~offset;
length = length || (buff.length - offset);
var result = [];
if (length === 4) {
// IPv4
for (var i = 0; i < length; i++) {
result.push(buff[offset + i]);
}
result = result.join('.');
} else if (length === 16) {
// IPv6
for (var i = 0; i < length; i += 2) {
result.push(buff.readUInt16BE(offset + i).toString(16));
}
result = result.join(':');
result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3');
result = result.replace(/:{3,4}/, '::');
}
return result;
};
ip.toBuffer = function (ip, buff, offset) {
offset = ~~offset;
var result;
if (this.isV4Format(ip)) {
result = buff || new Buffer(offset + 4);
ip.split(/\./g).map(function (byte) {
result[offset++] = parseInt(byte, 10) & 0xff;
});
} else if (this.isV6Format(ip)) {
var sections = ip.split(':', 8);
var i;
for (i = 0; i < sections.length; i++) {
var isv4 = this.isV4Format(sections[i]);
var v4Buffer;
if (isv4) {
v4Buffer = this.toBuffer(sections[i]);
sections[i] = v4Buffer.slice(0, 2).toString('hex');
}
if (v4Buffer && ++i < 8) {
sections.splice(i, 0, v4Buffer.slice(2, 4).toString('hex'));
}
}
if (sections[0] === '') {
while (sections.length < 8) sections.unshift('0');
} else if (sections[sections.length - 1] === '') {
while (sections.length < 8) sections.push('0');
} else if (sections.length < 8) {
for (i = 0; i < sections.length && sections[i] !== ''; i++);
var argv = [i, 1];
for (i = 9 - sections.length; i > 0; i--) {
argv.push('0');
}
sections.splice.apply(sections, argv);
}
result = buff || new Buffer(offset + 16);
for (i = 0; i < sections.length; i++) {
var word = parseInt(sections[i], 16);
result[offset++] = (word >> 8) & 0xff;
result[offset++] = word & 0xff;
}
}
if (!result) {
throw Error('Invalid ip address: ' + ip);
}
return result;
};