我正在寻找一个简单的函数(尽可能简单)来返回公共ip地址。 我遇到了这个功能:在javascript中获取公共ip地址
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;
,但它返回的本地ip地址。有任何想法吗?
您将需要使用其他来源来确定地址。本地机器通常不知道公共地址。 – Stese
好的,谢谢!我是JavaScript新手,我必须完成此任务。你能给我一个指导方针吗? – user7334203
你可能想要执行一个HTTP请求到ipify:https://api.ipify.org/ – briosheje