js获取本机ip地址

£神魔★判官ぃ 2022-08-30 05:15 384阅读 0赞
  1. //IP地址获取方法
  2. function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs
  3. //compatibility for firefox and chrome
  4. var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  5. var pc = new myPeerConnection({
  6. iceServers: []
  7. }),
  8. noop = function () {
  9. },
  10. localIPs = {},
  11. ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
  12. key;
  13. function iterateIP(ip) {
  14. if (!localIPs[ip]) onNewIP(ip);
  15. localIPs[ip] = true;
  16. }
  17. //create a bogus data channel
  18. pc.createDataChannel("");
  19. // create offer and set local description
  20. pc.createOffer().then(function (sdp) {
  21. sdp.sdp.split('\n').forEach(function (line) {
  22. if (line.indexOf('candidate') < 0) return;
  23. line.match(ipRegex).forEach(iterateIP);
  24. });
  25. pc.setLocalDescription(sdp, noop, noop);
  26. }).catch(function (reason) {
  27. // An error occurred, so handle the failure to connect
  28. });
  29. //sten for candidate events
  30. pc.onicecandidate = function (ice) {
  31. if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
  32. ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
  33. };
  34. }

浏览器修改设置

火狐

  • 输入about:config
  • 搜索media.peerconnection.ice.obfuscate_host_addresses,修改为false

谷歌

  • 搜索chrome://flags/#enable-webrtc-hide-local-ips-with-mdns
  • Anonymize local IPs exposed by WebRTC置为disabled
  • 新版该方法不可用

发表评论

表情:
评论列表 (有 0 条评论,384人围观)

还没有评论,来说两句吧...

相关阅读

    相关 用java获取IP地址

    在网上找了几个用java获取本机IP地址的代码,发现都少都有些不完美,自己整理了一下.突然之间很想把自己的IP地址给获取了,虽然用系统自带命令可以得到,但自己想写一个程序获取一

    相关 java获取IP地址方法

            在生产环境要是使用Spring定时任务的话,会在多台机器上定时启动相同的任务,为了保证只在一台机器上执行定时任务,我们在执行定时任务的时候先判断一下当前机器的I