当前位置:网站首页>nodejs获取客户端ip

nodejs获取客户端ip

2022-07-06 23:41:00 samscat

// 方法1
function getClientIp(req) {
    
    var ipAddress;
    var forwardedIpsStr = req.headers['X-Forwarded-For'];//判断是否有反向代理头信息
    if (forwardedIpsStr) {
    //如果有,则将头信息中第一个地址拿出,该地址就是真实的客户端IP;
        var forwardedIps = forwardedIpsStr.split(',');
        ipAddress = forwardedIps[0];
    }
    if (!ipAddress) {
    //如果没有直接获取IP;
        ipAddress = req.connection.remoteAddress;
    }
    return ipAddress;
};

// 方法2
 function getClientIp2(req) {
    
        return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
  };
  
const http = require('http')

const server = http.createServer()

//获取客户端真实ip
function getClientIp(req) {
    
  return req.headers['x-forwarded-for'] ||
  req.connection.remoteAddress ||
  req.socket.remoteAddress ||
  req.connection.socket.remoteAddress;
};

server.on('request',(req, res) => {
    
  const url = req.url;
  const method = req.method;
  
  const str = `您请求的地址:${
     url},请求方法:${
     method}`
  // 设置请求头,解决中文乱码问题
  res.setHeader('Content-Type','text/html;charset=utf-8')
  res.write('ip', 'utf8', () => {
    
    console.log('ippp', getClientIp(req))
  })

  // 发送数据给客户端和结束请求
  res.end(str)
})

server.listen('81',() => {
    
  console.log('start')
})
原网站

版权声明
本文为[samscat]所创,转载请带上原文链接,感谢
https://blog.csdn.net/samscat/article/details/125596596