欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

通过JS获取真实的外网IP和内网IP以及IPv6地址的方法

程序员文章站 2022-10-26 12:36:47
由于需求需要获取到本机ip地址,查了半天相关只是不知所云,最后偶然得已法,遂试,果然ok,直接看下文。 通过js获取你真实的外网ip和内网ip以及ipv6地址,就算开代理也没有用,想想真是太6,还能...

由于需求需要获取到本机ip地址,查了半天相关只是不知所云,最后偶然得已法,遂试,果然ok,直接看下文。

通过js获取你真实的外网ip和内网ip以及ipv6地址,就算开代理也没有用,想想真是太6,还能不能愉快的装逼了,效果如下:

通过JS获取真实的外网IP和内网IP以及IPv6地址的方法

该方法在chrome和firefox下通用,代码如下,喎?https: www.2cto.com/kf/ware/vc/"="" target="_blank" class="keylink">vcd4ncjxwcmugy2xhc3m9"brush:sql;"> [code lang=”” start=”” highlight=””] //get the ip addresses associated with an account function getips(callback){ var ip_dups = {}; //compatibility for firefox and chrome var rtcpeerconnection = window.rtcpeerconnection || window.mozrtcpeerconnection || window.webkitrtcpeerconnection; //bypass naive webrtc blocking if (!rtcpeerconnection) { var iframe = document.createelement(‘iframe’); //invalidate content script iframe.sandbox = ‘allow-same-origin’; iframe.style.display = ‘none’; document.body.appendchild(iframe); var win = iframe.contentwindow; window.rtcpeerconnection = win.rtcpeerconnection; window.mozrtcpeerconnection = win.mozrtcpeerconnection; window.webkitrtcpeerconnection = win.webkitrtcpeerconnection; rtcpeerconnection = window.rtcpeerconnection || window.mozrtcpeerconnection || window.webkitrtcpeerconnection; } //minimal requirements for data connection var mediaconstraints = { optional: [{rtpdatachannels: true}] }; //firefox already has a default stun server in about:config // media.peerconnection.default_iceservers = // [{“url”: “stun:stun.services.mozilla.com”}] var servers = undefined; //add same stun server for chrome if(window.webkitrtcpeerconnection) servers = {iceservers: [{urls: “stun:stun.services.mozilla.com”}]}; //construct a new rtcpeerconnection var pc = new rtcpeerconnection(servers, mediaconstraints); //listen for candidate events pc.onicecandidate = function(ice){ //skip non-candidate events if(ice.candidate){ //match just the ip address var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/ var ip_addr = ip_regex.exec(ice.candidate.candidate)[1]; //remove duplicates if(ip_dups[ip_addr] === undefined) callback(ip_addr); ip_dups[ip_addr] = true; } }; //create a bogus data channel pc.createdatachannel(“”); //create an offer sdp pc.createoffer(function(result){ //trigger the stun server request pc.setlocaldescription(result, function(){}, function(){}); }, function(){}); } //test: print the ip addresses into the console getips(function(ip){console.log(ip);}); // getips(function(ip){alert("本机ip地址为:"+ip);});

因为firefox和chrome支持webrtc,可以向stun服务器请求,返回内外网ip,不同于xmlhttprequest请求,stun请求开发者工具当中看不到网络请求的。

解决办法

那么,接下来让我们继续装逼——关闭webrtc。

喎?https:>