Last active
June 30, 2020 06:58
-
-
Save Richienb/737a0e30a3363478e4446f5f7fbcb5db to your computer and use it in GitHub Desktop.
internalIp.v4() for browsers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const internalIp = async () => { | |
if (!RTCPeerConnection) { | |
throw new Error("Not supported.") | |
} | |
const peerConnection = new RTCPeerConnection({ iceServers: [] }) | |
peerConnection.createDataChannel('') | |
peerConnection.createOffer(peerConnection.setLocalDescription.bind(peerConnection), () => { }) | |
peerConnection.addEventListener("icecandidateerror", (event) => { | |
throw new Error(event.errorText) | |
}) | |
return new Promise(async resolve => { | |
peerConnection.addEventListener("icecandidate", async ({candidate}) => { | |
peerConnection.close() | |
if (candidate && candidate.candidate) { | |
const result = candidate.candidate.split(" ")[4] | |
if (result.endsWith(".local")) { | |
const inputDevices = await navigator.mediaDevices.enumerateDevices() | |
const inputDeviceTypes = inputDevices.map(({ kind }) => kind) | |
const constraints = {} | |
if (inputDeviceTypes.includes("audioinput")) { | |
constraints.audio = true | |
} else if (inputDeviceTypes.includes("videoinput")) { | |
constraints.video = true | |
} else { | |
throw new Error("An audio or video input device is required!") | |
} | |
const mediaStream = await navigator.mediaDevices.getUserMedia(constraints) | |
mediaStream.getTracks().forEach(track => track.stop()) | |
resolve(internalIp()) | |
} | |
resolve(result) | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment