how to convert ipv6 address to ipv4 address in nodejs expressjs?
Asked Answered
G

2

8

Request object of NODEJS provides this method req.connection.remoteAddres to get the client's IP Address, but it gives the address in IPV6 format,how do I convert it into IPV4 format which is more readable ?

Gamin answered 2/11, 2017 at 9:17 Comment(2)
you are talking about impossible thing because you cant convert 128bit to 32bitFrohman
::ffff: is a subnet prefix for IPv4 (32 bit) addresses that are placed inside an IPv6 (128 bit) space.If you strip it off for aesthetic reasons, your code will break when it switches to an IPv6 network or it's confronted with an IPv6 address.Gothard
M
4

If the IPv6 address starts with ::ffff: then the client is communicating with IPv4 to an IPv6 application. In that case the remainder of the address is the IPv4 address. It might we written as ::ffff:10.11.12.13, in which case you can easily see the IPv4 address. It can also be written as ::ffff:0a0b:0c0d or ::ffff:a0b:c0d, in which case you need to convert the last part of the address from hexadecimal to decimal.

If the IPv6 address doesn't start with ::ffff: then the client is really communicating with IPv6, and no conversion is possible because IPv4 and IPv6 are different protocols with different addresses. Systems can have only IPv4, only IPv6 or a combination of both. There is no way for you to know that by looking at the address.

Mika answered 2/11, 2017 at 9:50 Comment(0)
L
4

The problem is because by default, NodeJS listens on IPv6 so it returns IPv6 addresses. If you tell it to only listen on IPv4 then you will only get IPv4 addresses, and they will be in the format you expect (no ::ffff: prefix).

How you do this depends on the library you're using, but typically where you specify the port to listen on, you can also specify a host/interface/IP and here you'd put in 0.0.0.0 to say "IPv4 only", as opposed the default :: which means IPv6+IPv4.

For example with the NodeJS socket library:

server.listen({
    port: 80,
    host: '0.0.0.0',
})

For WebSockets:

...listen(80, '0.0.0.0');
Lenes answered 11/5, 2021 at 5:48 Comment(1)
Thanks for the answer, should be accepted. If you are using express then it's called 'hostname'Gensmer

© 2022 - 2024 — McMap. All rights reserved.