Skip to content

Commit 97978b9

Browse files
authored
feat: add isLinkLocalIp function (#2863)
To detect when an IP address is link local, add a function,
1 parent a0c8ceb commit 97978b9

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

packages/utils/package.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@
8484
"types": "./dist/src/is-promise.d.ts",
8585
"import": "./dist/src/is-promise.js"
8686
},
87+
"./link-local-ip": {
88+
"types": "./dist/src/link-local-ip.d.ts",
89+
"import": "./dist/src/link-local-ip.js"
90+
},
8791
"./moving-average": {
8892
"types": "./dist/src/moving-average.d.ts",
8993
"import": "./dist/src/moving-average.js"

packages/utils/src/link-local-ip.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { isIPv4, isIPv6 } from '@chainsafe/is-ip'
2+
3+
export function isLinkLocalIp (ip: string): boolean {
4+
if (isIPv4(ip)) {
5+
return ip.startsWith('169.254.')
6+
}
7+
8+
if (isIPv6(ip)) {
9+
return ip.toLowerCase().startsWith('fe80')
10+
}
11+
12+
return false
13+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/* eslint-env mocha */
2+
3+
import { expect } from 'aegir/chai'
4+
import { isLinkLocalIp } from '../src/link-local-ip.js'
5+
6+
describe('isLinkLocalIp', () => {
7+
it('identifies link-local ip4 multiaddrs', () => {
8+
[
9+
'169.254.35.4',
10+
'169.254.35.4',
11+
'169.254.0.0',
12+
'169.254.255.255'
13+
].forEach(ma => {
14+
expect(isLinkLocalIp(ma)).to.be.true()
15+
})
16+
})
17+
18+
it('identifies non link-local ip4 multiaddrs', () => {
19+
[
20+
'101.0.26.90',
21+
'10.0.0.1',
22+
'192.168.0.1',
23+
'172.16.0.1'
24+
].forEach(ma => {
25+
expect(isLinkLocalIp(ma)).to.be.false()
26+
})
27+
})
28+
29+
it('identifies link-local ip6 multiaddrs', () => {
30+
[
31+
'fe80::1%lo0',
32+
'fe80::1%lo0',
33+
'fe80::1893:def4:af04:635a%en',
34+
'fe80::1893:def4:af04:635a',
35+
'fe80::1893:def4:af04:635a'
36+
].forEach(ma => {
37+
expect(isLinkLocalIp(ma)).to.be.true()
38+
})
39+
})
40+
41+
it('identifies non link-local ip6 multiaddrs', () => {
42+
[
43+
'2001:8a0:7ac5:4201:3ac9:86ff:fe31',
44+
'::'
45+
].forEach(ma => {
46+
expect(isLinkLocalIp(ma)).to.be.false()
47+
})
48+
})
49+
50+
it('identifies other multiaddrs as not link-local addresses', () => {
51+
[
52+
'wss0.bootstrap.libp2p.io',
53+
'wss0.bootstrap.libp2p.io'
54+
].forEach(ma => {
55+
expect(isLinkLocalIp(ma)).to.be.false()
56+
})
57+
})
58+
})

0 commit comments

Comments
 (0)