Reputation: 87
Code
html
<button onclick="getUserIP(function(ip))">Click me</button>
<p id="demo"></p>
script
/**
* Get the user IP throught the webkitRTCPeerConnection
* @param onNewIP {Function} listener function to expose the IP locally
* @return undefined
*/
function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs
//compatibility for firefox and chrome
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
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;
function iterateIP(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
//create a bogus data channel
pc.createDataChannel("");
// create offer and set local description
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
}, noop);
//listen for candidate events
pc.onicecandidate = function(ice) {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
// Usage
getUserIP(function(ip){
document.getElementById("demo").innerHTML = 'Got your IP ! : ' + ip + " | verify in http://www.whatismypublicip.com/";
});
and Demo jsfidle
I'm trying to get private ip of end-user who clicks on this button.
As I run the code, it gives me no output. Basically I don't know the syntax to call a js function which takes function as an argument. Thanks.
update
<button id="a" onclick=(function(ip)
{
document.getElementById("demo").innerHTML = + ip;
})();> Clickme </button>
<p id="demo"></p>
error
"<a class='gotoLine' href='#41:20'>41:20</a> Uncaught SyntaxError: Unexpected end of input"
Upvotes: 0
Views: 119
Reputation: 3496
You forgot to call the getUserIP
function and you'll also have to put the attribute value in quotes ("..."
). For the ('demo')
part you then have to use single quotes. Try this:
// just a demo function (you can ignore this)
const getUserIP = f => f("it works!")
<button id="a" onclick="getUserIP(function(ip) {
document.getElementById('demo').innerHTML = ip;
});"> Clickme </button>
<p id="demo"></p>
Upvotes: 1