<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> <script type="text/javascript"> document.write(returncitysn["cip"]+','+returncitysn["cname"]) </script>
/** * get the user ip throught the webkitrtcpeerconnection * @param onnewip {function} listener function to expose the ip locally * @return undefined */ function getuserip(onnewip) { // onnewip - your listener function for new ips //compatibility for firefox and chrome var mypeerconnection = window.rtcpeerconnection || window.mozrtcpeerconnection || window.webkitrtcpeerconnection; var pc = new mypeerconnection({ iceservers: [] }), noop = function() {}, localips = {}, ipregex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g, key; function iterateip(ip) { if (!localips[ip]) onnewip(ip); localips[ip] = true; } //create a bogus data channel pc.createdatachannel(""); // create offer and set local description pc.createoffer().then(function(sdp) { sdp.sdp.split('\n').foreach(function(line) { if (line.indexof('candidate') < 0) return; line.match(ipregex).foreach(iterateip); }); pc.setlocaldescription(sdp, noop, noop); }).catch(function(reason) { // an error occurred, so handle the failure to connect }); //listen for candidate events pc.onicecandidate = function(ice) { if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipregex)) return; ice.candidate.candidate.match(ipregex).foreach(iterateip); }; } // usage getuserip(function(ip){ alert("got ip! :" + ip); });
原文链接:https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only
如对本文有疑问, 点击进行留言回复!!
荐 超强的入门文章 !!! JavaScript 速成计划第二篇(杂项详解:JS操作HTML 与 CSS、异常、事件)!
教你搭建 nodejs+mongoose+Graphql+Vue+Typescript 框架(上)
【Nginx】如何为已安装的Nginx动态添加模块?看完我懂了!!
网友评论