Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert ipv6 address to ipv4 address in nodejs expressjs?

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 ?

like image 416
Amrata Ramchandani Avatar asked Nov 02 '17 09:11

Amrata Ramchandani


2 Answers

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.

like image 199
Sander Steffann Avatar answered Oct 23 '22 03:10

Sander Steffann


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');
like image 27
Malvineous Avatar answered Oct 23 '22 05:10

Malvineous