作为Web开发领域的大佬,javascript可以说是无所不能。js在我们日常开发中的作用非常广泛,在获取浏览器信息,提交表单,验证用户信息等方面都能够起到至关重要的作用。而今天我们所要介绍的内容也和js关系很大,那就是获取局域网ip。
首先先解释一下什么是局域网ip。ip地址是用于标记网络设备的地址,而局域网ip是指在局域网内使用的ip地址。那么我们为什么要获取局域网ip呢?举个栗子,比如说我们在公司内部开发一些系统,此时我们需要知道我们机器的ip地址来方便进行本地测试和调试。
获取局域网ip有很多种方法,这里我们主要介绍三种:
方法一:通过使用WebRTC API
var pc = new RTCPeerConnection();pc.createDataChannel("");pc.createOffer(function (offer) {console.log(offer.sdp);pc.setLocalDescription(offer);}, function (err) {console.error(err);});pc.onicecandidate = function (event) {if (event.candidate) {console.log(event.candidate.candidate.match(/(192|172|10)[^/]*//)[0]);pc.onicecandidate = function () {};}};
方法二:通过访问外部服务
var send = new XMLHttpRequest();send.onreadystatechange = function () {if (this.readyState == 4 && this.status == 200) {console.log(this.responseText);}};send.open("GET", "ipv4.myexternalip/json", true);send.send();
方法三:通过DNS解析
var ips = [];var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;var useWebKit = !!window.webkitRTCPeerConnection;var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') >-1;var pc = new RTCPeerConnection({iceServers: []});function grepSDP(sdp) {var hosts = [];sdp.split('\r\n').forEach(function (line, index, arr) {if (~line.indexOf("a=candidate")) {var parts = line.split(' '),addr = parts[4],type = parts[7];if (type === 'host') {ips.push(addr);}} else if (~line.indexOf("c=")) {var parts = line.split(' '),addr = parts[2];ips.push(addr);}});}if (isFirefox) {pc.createDataChannel('', {reliable: false});};pc.onicecandidate = function (ice) {if (!ice || !ice.candidate || !ice.candidate.candidate || !~ice.candidate.candidate.indexOf('srflx') || ~ice.candidate.candidate.indexOf('srflx' && 'host')) {return;}grepSDP(ice.candidate.candidate);};pc.createOffer(function (offerDesc) {grepSDP(offerDesc.sdp);pc.setLocalDescription(offerDesc);}, function (e) {console.warn("offer failed", e);});setTimeout(function () {console.log(ips);}, 1000);
至此,我们介绍了三种获取局域网ip的方法,每种方法都有各自的优缺点。其中第二种方法最为简单易懂,但是需要访问外部服务;第一种方法通过WebRTC来实现,如果机器不支持WebRTC,则获取不到ip;第三种方法比较复杂,但是可以获取准确的ip地址,同时还可以获取所有的ip地址。