Skip to content

Instantly share code, notes, and snippets.

@stenito
Last active February 15, 2021 12:39
Show Gist options
  • Save stenito/08a855d30b5615abb584147c014b66e1 to your computer and use it in GitHub Desktop.
Save stenito/08a855d30b5615abb584147c014b66e1 to your computer and use it in GitHub Desktop.
Get public IP address (wan IP address) using XMLHttpRequest JavaScript function
function getPublicIP() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://httpbin.org/ip", true); // false for synchronous request
xhr.onload = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let yourWanIP = JSON.parse(xhr.responseText).origin;
// do what you want to do with the IP address
// ... eg. log it to the console
console.log(yourWanIP);
} else {
console.error(xhr.statusText);
}
}
}
xhr.onerror = function(e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
getPublicIP();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment