JS通過webRTC獲取設(shè)備IP

RTCPeerConnection?接口代表一個由本地計算機到遠端的WebRTC連接。該接口提供了創(chuàng)建,保持,監(jiān)控,關(guān)閉連接的方法的實現(xiàn)

WebRTC在瀏覽器中的兼容性。參考:

var PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;

(其他請查看https://developer.mozilla.org/zh-CN/docs/Web/API/RTCPeerConnection)

構(gòu)造函數(shù):RTCPeerConnection.RTCPeerConnection()?,創(chuàng)建一個新的RTCPeerConnection對象。

/**

* 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://www.cnblogs.com/zyh-club/p/11097418.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容