Last active
February 15, 2021 12:39
-
-
Save stenito/08a855d30b5615abb584147c014b66e1 to your computer and use it in GitHub Desktop.
Get public IP address (wan IP address) using XMLHttpRequest JavaScript function
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
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