直接上代码:
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() {}, ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g, key; var this_ip = '' function iterateIP(ip) { if (ip && ip != '127.0.0.1') { this_ip=ip onNewIP(ip); } } //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 }); //sten for candidate events pc.onicecandidate = function(ice) { if(this_ip){ return false; } if (ice) { if (ice.candidate && ice.candidate.candidate) { var matchArr = ice.candidate.candidate.match(ipRegex) if (matchArr) { matchArr.forEach(iterateIP); } } else if ((ice.currentTarget && ice.currentTarget.localDescription) || (ice.target && ice.target.localDescription)) { var ipStr = '' if (ice.currentTarget.localDescription) { ipStr = ice.currentTarget.localDescription.sdp } else if (ice.target.localDescription) { ipStr = ice.target.localDescription.sdp } if (ipStr) { var matchArr = ipStr.match(ipRegex) if (matchArr) { matchArr.forEach(iterateIP); } } } } }; } // Usage getUserIP(function(ip) { console.log("Got IP! :" + ip); });
整体部分来自:https://blog.csdn.net/qq_37837478/article/details/82966064
但是做了兼容移动端的处理,代码还可以再精简,但是懒得改了,凑合用吧
未经允许不得转载:前端撸码笔记 » 利用webRTC获取本机ip(兼容移动端)