Skip to content

Instantly share code, notes, and snippets.

@frectonz
Created August 24, 2025 18:21
Show Gist options
  • Select an option

  • Save frectonz/81257238351a642a842959dfd3259b6c to your computer and use it in GitHub Desktop.

Select an option

Save frectonz/81257238351a642a842959dfd3259b6c to your computer and use it in GitHub Desktop.
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