I am attempting to save a user’s local IP address to a variable in JavaScript. I found part of the solution in a post by mido in an earlier question titled How to get client’s IP address using javascript only?. The solution works well and uses WebRTC with JavaScript to display the local IP; however, I have been unable to pass these IP addresses to a variable. The code below shows what I am trying to do.
In it, I have created an html tag with id=saveIP. I am trying to replace its contents with the user's IP (IPv4 for the moment). I created a varialbe window.saveIP for this purpose, and I'm using the document.getElementById('saveIP').innerHTML method towards the bottom of the script to pass the value to my HTML tag.
I have seen other solutions, but they all appear to simply display the IP address without saving them.
My question is what modifications must I make to capture the user's local IP(s) and save it to a variable?
<html>
<body>
<p id=saveIP> Replace this with IP </p>
<script>
function findIP(onNewIP) { // onNewIp - your listener function for new IPs
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
var pc = new myPeerConnection({iceServers: []}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
//window.saveIP = pc;
//window.saveIP = localIPs; // Returns [object, object] or JSON.stringfy returns {}
function ipIterate(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(ipIterate);
});
pc.setLocalDescription(sdp, noop, noop);
}, noop); // create offer and set local description
pc.onicecandidate = function(ice) { //listen for candidate events
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
}
var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);
function addIP(ip) {
console.log('got ip: ', ip);
var li = document.createElement('li');
li.textContent = ip;
window.saveIP = ip; // <--value captured is [object HTMLParagraph]; JSON.stringify returns {}
ul.appendChild(li);
}
findIP(addIP);
document.getElementById('saveIP').innerHTML = JSON.stringify(window.saveIP);
</script>
</body>
</html>