簡體   English   中英

在JavaScript中獲取公共IP地址

[英]Get public ip address in 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;

但它返回本地ipAddress。 有任何想法嗎?

 $(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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM