nodejs获取 本地ip地址

寻技术 JS脚本 / Node.Js 2024年01月17日 70

vue本地项目,想要在手机端访问的时候,需要在vue.config.js的devServe中修改 host的值

host: "localhost"  ==>  host: "**.**.**.**"

 但每次启动前都要手动查询ipconfig/ifconfig,比较麻烦。

所以,用nodejs的‘os’来自动获取本地ip

 'use strict'
 const os = require('os')
 
 /**
  * 获取当前机器的ip地址
  */
 function getIpAddress() {
   var interfaces=os.networkInterfaces()
 
   for (var dev in interfaces) {
     let iface = interfaces[dev]
 
     for (let i = 0; i < iface.length; i++) {
       let {family, address, internal} = iface[i]
 
       if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
         return address
       }
     }
   }
 }
 
 const ipAddress = getIpAddress()
 console.log(ipAddress)
 
 module.exports = {
   ipAddress
 }

 

 

 

 

 


 
                    
            
                
关闭

用微信“扫一扫”