获取本机IP地址的实例(JavaScript / Node.js)
程序员文章站
2022-03-20 21:55:00
--web 客户端javascript
&l...
--web 客户端javascript
<!-- 调用方式 --> <body onload="checkcookie()"></body> function getyourip() { const rtcpeerconnection = window.rtcpeerconnection || window.webkitrtcpeerconnection || window.mozrtcpeerconnection; if (rtcpeerconnection) (function() { const rtc = new rtcpeerconnection({iceservers: []}); if (1 || window.mozrtcpeerconnection) { rtc.createdatachannel('', {reliable: false}); } rtc.onicecandidate = function(evt) { if (evt.candidate) grepsdp(`a=${evt.candidate.candidate}`); }; rtc.createoffer(function(offerdesc) { grepsdp(offerdesc.sdp); rtc.setlocaldescription(offerdesc); }, function(e) {console.warn('offer failed', e);}); const addrs = object.create(null); addrs['0.0.0.0'] = false; function updatedisplay(newaddr) { if (newaddr in addrs) return; addrs[newaddr] = true; const displayaddrs = object.keys(addrs).filter(function(k) {return addrs[k];}); for (let i = 0; i < displayaddrs.length; i++) { if (displayaddrs[i].length > 16) { displayaddrs.splice(i, 1); i--; } } console.info('您的ip: ', displayaddrs[0]); } function grepsdp(sdp) { sdp.split('\r\n').foreach(function(line, index, arr) { if (~line.indexof('a=candidate')) { const parts = line.split(' '), addr = parts[4], type = parts[7]; if (type === 'host') updatedisplay(addr); } else if (~line.indexof('c=')) { const parts = line.split(' '), addr = parts[2]; updatedisplay(addr); } }); } })(); else { console.warn('请使用主流浏览器:chrome,firefox,opera,safari'); } }
--web服务端node.js
const os = require('os'); module.exports = { getlocalip : function() { const eth0 = os.networkinterfaces().eth0; let localhost = null; for (let i = 0; i < eth0.length; i++) { if (eth0[i].family == 'ipv4') { localhost = eth0[i].address; } } return localhost; }, };
以上这篇获取本机ip地址的实例(javascript / node.js)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: 基于Python的人脸自动戴口罩系统