Stripping "::ffff:" prefix from request.connection.remoteAddress nodejs

If you want to get the ip address of IPv4, you can use:

http.createServer(callback).listen(port, '0.0.0.0');

then, you will get what you want

req.connection.remoteAddress   // 192.168.1.10

Here is the relevant document of nodejs


app.post('/xyz',function(request,response)
{
    var IPFromRequest=request.connection.remoteAddress;
    var indexOfColon = IPFromRequest.lastIndexOf(':');
    var IP = IPFromRequest.substring(indexOfColon+1,IPFromRequest.length);
    console.log(IP);
});

I would split the remoteAddress ::ffff:192.168.1.10 by the : delimiter and simply take the value of the output array at index array.length - 1

like so:

const remoteAddress = '::ffff:192.168.0.3'
const array = remoteAddress.split(':')
const remoteIP = array[array.length - 1]
console.log(remoteIP)

prints out 192.168.0.3


Yes, it's safe to strip. Here's a quick way to do it.

address.replace(/^.*:/, '')

What happens is your OS is listening with a hybrid IPv4-IPv6 socket, which converts any IPv4 address to IPv6, by embedding it within the IPv4-mapped IPv6 address format. This format just prefixes the IPv4 address with :ffff:, so you can recover the original IPv4 address by just stripping the :ffff:. (Some deprecated mappings prefix with :: instead of :ffff:, so we use the regex /^.*:/ to match both forms.)

If you aren't sure that incoming IPv6 address came from an IPv4, you can check that it matches the IPv6-mapping template first:

template = /^:(ffff)?:(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/
has_ipv4_version = template.test(address)