Express.js req.ip is returning ::ffff:127.0.0.1

前端 未结 8 718
谎友^
谎友^ 2020-12-02 06:37

I am currently trying to get the IP of the requested user. The problem is the IP is returning ::ffff:127.0.0.1 instead of 127.0.0.1. I tried using

8条回答
  •  [愿得一人]
    2020-12-02 07:14

    This seems to be a quirk of ipv6: for ipv4 addresses, ipv6 seems to mix ipv6 notation with ipv4 notation.

    In order to get both ipv4 and ipv6 addresses in the simple, unmixed notation, I am using:

    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    if (ip.substr(0, 7) == "::ffff:") {
      ip = ip.substr(7)
    }
    

提交回复
热议问题