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"
function(ip)is not a valid function definition and will throw a SyntaxError. If you really want to define the callback within the onclick attribute try this:function(ip) { /* your code */ }onclick="getUserIP(function(ip))makes no sense, asgetUserIP's parameter needs to be an actual function.