2

I want to get an ip to record user logins.

I tried nestjs-real-ip and @Ip().

And I tried to log in through my mobile phone and pc browser,

but all of them show :::1. How do I get the client's real IP?

2 Answers2

6

:::1 is the loopback address in ipv6, equal to 127.0.0.1 in ipv4. You see that address since you're trying to access localhost locally. this is just how your browser shows it to you.

If you'll access the server through your IP and try to test it using curl you might see something else, e.g.:

curl localhost:3000/ip
::ffff:127.0.0.1

or

curl 174.38.167.56:3000/ip
::ffff:174.38.167.56

If you want to know more about that ffff prefix, here

BTW - you don't need any additional library. In express, request.ip will give you the same answer. here's a snippet:

import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';

@Controller('ip')
export class IpController {
    @Get()
    getIpAddressFromRequest(@Req() request: Request): string {
        return request.ip;
    }
}
SyntaxError
  • 179
  • 8
0

Based on the Nestjs docs, You can use a decorator named Ip as follow

import { Get, Ip } from "@nestjs/common"

@Get('my-ip')
async getMyIp(@Ip() ip){
  return ip;
}
Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79