Reputation: 7334
I'm looking for a simple function (as simple as it can be) for returning the public ip address. I came across this function:
const clientsIpAdress = (onNewIP) => {
const MyPeerConnection =
window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
const pc = new MyPeerConnection({
iceServers: []
});
const noop = () => {};
const localIPs = {};
const ipRegex =
/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
const iterateIP = (ip) => {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
};
pc.createDataChannel('');
pc.createOffer().then((sdp) => {
sdp.sdp.split('\n').forEach((line) => {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
});
pc.onicecandidate = (ice) => {
if (!ice || !ice.candidate ||
!ice.candidate.candidate ||
!ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
};
export default clientsIpAddress;
but it is returning the local ipAddress. Any ideas?
Upvotes: 1
Views: 3860
Reputation: 774
$(document).ready(function () {
$.getJSON("http://jsonip.com/?callback=?", function (data) {
console.log(data);
alert(data.ip);
});
});
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
</html>
Upvotes: 2