-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffscreen.js
More file actions
42 lines (34 loc) · 1.1 KB
/
offscreen.js
File metadata and controls
42 lines (34 loc) · 1.1 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
async function detectLanIPv4() {
const ips = new Set();
const peerConnection = new RTCPeerConnection({ iceServers: [] });
peerConnection.createDataChannel("x");
peerConnection.onicecandidate = (e) => {
const candidate = e?.candidate?.candidate;
if (!candidate) {
return;
}
const m = candidate.match(/\b(\d{1,3}(?:\.\d{1,3}){3})\b/);
if (m?.[1]) ips.add(m[1]);
};
await peerConnection.setLocalDescription(await peerConnection.createOffer());
await new Promise((r) => setTimeout(r, 800));
peerConnection.close();
return [...ips].filter((ip) => isPrivate(ip) && !ip.startsWith("127."))[0] || "";
}
function isPrivate(ip) {
const [a, b] = ip.split(".").map((n) => parseInt(n, 10));
if ([a, b].some(Number.isNaN)) {
return false;
}
return (
a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168)
);
}
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg?.type === "GET_LAN_IP") {
detectLanIPv4()
.then((ip) => sendResponse({ ip }))
.catch(() => sendResponse({ ip: "" }));
return true;
}
});