-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
46 lines (38 loc) · 1.24 KB
/
index.js
File metadata and controls
46 lines (38 loc) · 1.24 KB
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
import * as bit64 from '@mfelements/bit64'
const local4 = [
'10.0.0.0/8',
'127.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
];
const localHosts = /^((.+\.local)|localhost|loopback)$/;
function ipToNum(ip){
return Number.parseInt(ip.split('.').map(v => (+v).toString(16).padStart(2, '0')).join(''), 16)
}
function numToIp(num){
return num.toString(16).padStart(8, '0').split(/(.{2})/).filter(v => v).map(v => parseInt(v, 16)).join('.')
}
function mask(size){
return parseInt(''.padStart(size, '1').padEnd(32, '0'), 2)
}
function inRange(ip, range){
const [ rangeIp, bits ] = range.split('/');
const bitMask = mask(+bits);
const from = bit64.and(ipToNum(rangeIp), bitMask);
const to = from + bit64.xor(bitMask, 0xffffffff);
const numIp = ipToNum(ip);
return numIp >= from && numIp <= to
}
function isIp(hostname){
const numeric = /^(\d+\.){3}\d+$/.test(hostname);
if(!numeric) return false;
const [ p0, p1, p2, p3 ] = hostname.split('.').map(v => +v < 256);
return p0 && p1 && p2 && p3
}
export default class Hostname{
constructor(name){
this.local = isIp(name)
? local4.map(mask => inRange(name, mask)).reduce((p, c) => p || c)
: localHosts.test(name)
}
}