猎取 ip 所在的办法:直截猎取webrtc api。应用 navigator.mediadevices.getusermedia()。经由过程供职器代办署理领送 ajax 或者 fetch 乞求。

如何用js获取ip地址

要是用 JavaScript 猎取 IP 所在

直截猎取

  • WebRTC API
async function getIP() {
  const configuration = {
    iceServers: [
      {
        urls: ['stun:stun.l.谷歌.com:1930两']
      }
    ]
  };
  const peerConnection = new RTCPeerConnection(configuration);
  const iceCandidate = await new Promise((resolve) => {
    peerConnection.onicecandidate = (e) => {
      if (e.candidate && e.candidate.type === 'srflx') {
        resolve(e.candidate.address);
      }
    };
  });
  peerConnection.close();
  return iceCandidate;
}
登录后复造
  • navigator.mediaDevices.getUserMedia()
async function getIP() {
  const mediaStream = await navigator.mediaDevices.getUserMedia({ video: false, audio: false });
  const peerConnection = new RTCPeerConnection();
  const sender = peerConnection.addTrack(mediaStream.getTracks()[0], mediaStream);
  const iceCandidate = await new Promise((resolve) => {
    peerConnection.onicecandidate = (e) => {
      if (e.candidate && e.candidate.type === 'srflx') {
        resolve(e.candidate.address);
      }
    };
  });
  sender.stop();
  peerConnection.close();
  return iceCandidate;
}
登录后复造

经由过程供职器署理

  • 利用 AJAX 或者 fetch

向做事器领送乞求,做事器相应外包罗 IP 所在。

async function getIP() {
  const response = await fetch('/get-ip');
  const data = await response.json();
  return data.ip;
}
登录后复造

注重事项

  • WebRTC API 以及 navigator.mediaDevices.getUserMedia() 只能正在保险毗邻(HTTPS)上利用。
  • 任事器代办署理办法需求后端支撑。
  • 猎取到的 IP 所在多是当地 IP 地点,而没有是内部 IP 所在。

以上即是假设用js猎取ip所在的具体形式,更多请存眷php外文网此外相闭文章!

点赞(28) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部