直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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(兼容移动端)