Created
August 24, 2025 18:21
-
-
Save frectonz/81257238351a642a842959dfd3259b6c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| async function getPublicIP(): Promise<string | null> { | |
| return new Promise((resolve) => { | |
| const pc = new RTCPeerConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] }); | |
| pc.createDataChannel(""); | |
| pc.onicecandidate = (event: RTCPeerConnectionIceEvent) => { | |
| if (!event.candidate) return resolve(null); | |
| const parts = event.candidate.candidate.split(" "); | |
| const ip = parts[4]; | |
| const type = parts[7]; | |
| if (type === "srflx" || type === "relay") { | |
| resolve(ip); | |
| } | |
| }; | |
| pc.createOffer() | |
| .then((offer: RTCSessionDescriptionInit) => pc.setLocalDescription(offer)) | |
| .catch(() => resolve(null)); | |
| }); | |
| } | |
| // Usage | |
| (async () => { | |
| const ip: string | null = await getPublicIP(); | |
| console.log(ip); // e.g., "102.218.50.236" or null | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment