NodeJs既可以获取服务器端ip地址(也就是咱们的本机地址),也可以获取客户端(也就是浏览器)的地址,具体代码如下:

NodeJS获取服务器端的ip地址

  • 新建getip.js,代码如下:

    //获取本机ip地址
    function getIPAdress() {
        var interfaces = require('os').networkInterfaces();  
        for (var devName in interfaces) {    
            var iface = interfaces[devName];      
            for (var i = 0; i < iface.length; i++) {
                var alias = iface[i];
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    return alias.address;
                }
            }  
        }
    }
    
    var ip = getIPAdress();
    console.log("\n--------IP地址:" + ip+ "------\n");
    
  • 终端执行:node getip.js

  • 结果如下:

    效果图

NodeJs获取客服端ip地址

  • 需要启动服务才行,这里只是简单的列出出来了大致的方法,具体如下:

    //获取客户端ip地址
    function getClientIp(req) {
        var ip = req.headers['x-forwarded-for'] ||
            req.ip ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress || '';
        if(ip.split(',').length>0){
            ip = ip.split(',')[0]
        }
        ip = ip.substr(ip.lastIndexOf(':')+1,ip.length);
        console.log("ip:"+ip);
        return ip;  
    };
    

详见【demo

以上文章来自:黄卉 , https://huanghui8030.github.io/node/getip.html