528

How can I determine the IP address of a given request from within a controller? For example (in express):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})
5
  • 51
    If you are using Express you can use req.ip source - expressjs.com/en/api.html#req.ip Commented Jul 26, 2016 at 6:14
  • Try this: github.com/indutny/node-ip Commented Jan 4, 2017 at 16:16
  • 67
    For those who are working from localhost - like I did, the result for all answer below(Nearly all the answers works) might come ::1. This got me confused for sometime. Later found out that ::1 is real IP Address and is IPV6 notation for localhost. Hope this helps someone Commented Sep 14, 2018 at 11:44
  • 1
    Cloudflare get client IP req.headers['cf-connecting-ip'] Commented May 10, 2022 at 5:54
  • When I do this on a deployed server, it seems I get ::ffff:[my ipv4 address]. But ffff is not my ipv6 address, does anyone know what that is for?
    – Brian
    Commented Dec 20, 2023 at 0:04

34 Answers 34

655

In your request object there is a property called socket, which is a net.Socket object. The net.Socket object has a property remoteAddress, therefore you should be able to get the IP with this call:

request.socket.remoteAddress

(if your node version is below 13, use the deprecated now request.connection.remoteAddress)

EDIT

As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['x-forwarded-for']

EDIT 2

When using express with Node.js:

If you set app.set('trust proxy', true), req.ip will return the real IP address even if behind proxy. Check the documentation for further information

18
  • 15
    This gives me an IP address different from what whatismyip.com gives me. Why would that be?
    – Shamoon
    Commented Nov 12, 2011 at 22:23
  • 5
    I have my API service installed on a no.de instance. When I try to access it from my computer, I get an IP address of "10.2.XXX.YYY" whereas my real world IP is "67.250.AAA.BBB"
    – Shamoon
    Commented Nov 12, 2011 at 22:36
  • 8
    it's request.headers['X-Forwarded-For']
    – 0x6A75616E
    Commented Nov 13, 2011 at 0:42
  • 5
    Note that net.Stream is now net.Socket, and the documentation lives here: nodejs.org/api/net.html#net_class_net_socket
    – monsur
    Commented Mar 1, 2013 at 5:02
  • 11
    For anyone whose interested, for Heroku it's: request.headers['x-forwarded-for'] Commented Oct 22, 2014 at 10:51
535
var ip = req.headers['x-forwarded-for'] ||
     req.socket.remoteAddress ||
     null;

Note that sometimes you can get more than one IP address in req.headers['x-forwarded-for']. Also, an x-forwarded-for header will not always be set which may throw an error.

The general format of the field is:

x-forwarded-for: client, proxy1, proxy2, proxy3

where the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1, proxy2, and then proxy3. proxy3 appears as remote address of the request.

This is the solution suggested by Arnav Gupta with a fix Martin has suggested below in the comments for cases when x-forwarded-for is not set :

var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() || 
         req.socket.remoteAddress

Suggestion using modern JS:

  • processing x-forwarded-for only if set, if so, take the first address
  • other parameters use optional chaining (?.)
const parseIp = (req) =>
    req.headers['x-forwarded-for']?.split(',').shift()
    || req.socket?.remoteAddress

console.log(parseIp(req))
// => 127.0.0.1
21
  • 22
    How to prevent spoofing of these headers though?
    – Domi
    Commented May 27, 2014 at 11:21
  • 8
    This usually works well but for some reason I recently got the error "Cannot read property 'remoteAddress' of undefined" because apparently everything was null/undefined, including req.connection.socket. I'm not sure why/what conditions cause that to be the case but it would be good to check that req.connection.socket exists to avoid your server crashing if this happens. Commented Nov 14, 2014 at 20:02
  • 9
    Last line req.connection.socket.remoteAddress throwing error. Be carefully.
    – yAnTar
    Commented Dec 18, 2014 at 16:57
  • 25
    The returned ip address is ::1. Why?
    – Bagusflyer
    Commented Feb 11, 2016 at 3:10
  • 6
    @bagusflyer this is your localhost IP address Commented Jun 26, 2016 at 15:49
147

If using express...

req.ip

I was looking this up then I was like wait, I'm using express. Duh.

2
36

You can stay DRY and just use node-ipware that supports both IPv4 and IPv6.

Install:

npm install ipware

In your app.js or middleware:

var getIP = require('ipware')().get_ip;
app.use(function(req, res, next) {
    var ipInfo = getIP(req);
    console.log(ipInfo);
    // { clientIp: '127.0.0.1', clientIpRoutable: false }
    next();
});

It will make the best attempt to get the user's IP address or returns 127.0.0.1 to indicate that it could not determine the user's IP address. Take a look at the README file for advanced options.

9
  • 47
    " or returns 127.0.0.1 to indicate that it could not determine the user's IP address" There is quite a big difference between 127.0.0.1 and unknown...
    – Nepoxx
    Commented Mar 13, 2015 at 13:15
  • 7
    It returned something weird for me :ffff:(not my IP address) when tested from Heroku. @edmar-miyake's answer is working properly for me.
    – Nilloc
    Commented Apr 11, 2015 at 5:15
  • I wonder what the would IP be if you were to use the right2left lookup in the 'x-forwarded-for' case. var ip_info = get_ip(req, right_most_proxy=True), as in some setup, the client IP might be the right most IP.
    – Avid Coder
    Commented Apr 15, 2015 at 20:54
  • 4
    That method is returning clientIp: '::1' for me. It doesn't seem to work. Commented Jan 11, 2016 at 11:48
  • 1
    @GervasiusTwinklewinkleson The client's request provides the server with only one IP address, so it will be either IPv4, IPv6, or IPv4 wrapped in IPv6.
    – Avid Coder
    Commented Sep 20, 2023 at 13:18
28

You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.

Disclosure: I created this module

Install:

npm install request-ip

In your app:

var requestIp = require('request-ip');

// inside middleware handler
var ipMiddleware = function(req, res, next) {
    var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
    next();
};

Hope this helps

5
  • 4
    checking the source code of the package request-ip at github.com/pbojinov/request-ip/blob/master/index.js it checks x-forwarded-for and all sorts of other headers for popular load balancers like AWS ELB, Cloudflare, Akamai, nginx, Rackspace LB and Riverbed's Stingray
    – Giorgio
    Commented Oct 19, 2017 at 11:39
  • 1
    it returns null for me. Commented Jun 18, 2019 at 10:00
  • The same thing instead use request.headers['x-forwarded-for'] Commented Jan 24, 2020 at 7:35
  • @pbojinov if a client has both ipv4 and ipv6 I guess there is no way to get both? Commented Sep 19, 2023 at 9:07
  • request.headers['x-forwarded-for'] is one of the many headers that can potentially contain the user's IP. That's why I set out to create the request-ip package.
    – pbojinov
    Commented Oct 4, 2023 at 2:57
19

request.headers['x-forwarded-for'] || request.connection.remoteAddress

If the x-forwarded-for header is there then use that, otherwise use the .remoteAddress property.

The x-forwarded-for header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because the request.connection.remoteAddress the property will contain the private IP address of the load balancer rather than the public IP address of the client. By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.

1
  • request.connection is deprecated, use socket instead.
    – GorvGoyl
    Commented Jun 5, 2021 at 19:12
19

I have tried all of them didn't work though,

console.log(clientIp);
console.log(req.ip);

console.log(req.headers['x-forwarded-for']);
console.log(req.connection.remoteAddress);
console.log(req.socket.remoteAddress);
console.log(req.connection.socket.remoteAddress.split(",")[0]);

When running an Express app behind a proxy for me Nginx, you have to set the application variable trust proxy to true. Express offers a few other trust proxy values which you can review in their documentation, but below steps worked for me.

  1. app.set('trust proxy', true) in your Express app.

app.set('trust proxy', true);

  1. Add proxy_set_header X-Forwarded-For $remote_addr in the Nginx configuration for your server block.
  location /  {
                proxy_pass    http://localhost:3001;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $remote_addr;  # this line
                proxy_cache_bypass $http_upgrade; 
        }
  1. You can now read off the client’s IP address from the req.header('x-forwarded-for') or req.connection.remoteAddress; Full code for ipfilter
module.exports =  function(req, res, next) {
    let enable = true; // true/false
    let blacklist = ['x.x.x.x'];
    let whitelist = ['x.x.x.x'];
    let clientIp = req.header('x-forwarded-for') || req.connection.remoteAddress;
    if (!clientIp) {
        return res.json('Error');
    }
    if (enable
        && paths.some((path) => (path === req.originalUrl))) {

        let blacklist = blacklist || [];
        if (blacklist.some((ip) => clientIp.match(ip) !== null)) {
            return res.json({ status: 401, error: 'Your IP is black-listed !'});
        }
        let whitelist = whitelist || [];
        if (whitelist.length === 0 || whitelist.some((ip) => clientIp.match(ip) !== null)) {
            next();
            return;
        } else {
            return res.json({ status: 401, error: 'Your IP is not listed !'});
        }
    }
    next();
};
1
  • 3
    Thank you for this! This is ultimately what got me up and running -- the modification to nginx.conf (which nobody else mentioned, oddly).
    – Netside
    Commented Oct 25, 2020 at 3:27
18

Following Function has all the cases covered will help

var ip;
if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}console.log("client IP is *********************" + ip);
3
  • Note the ips are have a , between for me. Commented Oct 6, 2016 at 0:15
  • Out of all the answers, I think this one is the best. It is comprehensive, and defensively coded with "look before you leaps".
    – KANJICODER
    Commented Sep 11, 2020 at 17:53
  • request.connection is deprecated, use socket instead
    – GorvGoyl
    Commented Jun 5, 2021 at 19:12
15

Warning:

Don't just blindly use this for important rate-limiting:

let ip = request.headers['x-forwarded-for'].split(',')[0];

It's very easy to spoof:

curl --header "X-Forwarded-For: 1.2.3.4" "https://example.com"

In that case ther user's real IP address will be:

let ip = request.headers['x-forwarded-for'].split(',')[1];

I'm surprised that no other answers have mentioned this.

1
  • 4
    The top answer does handle this by pop()ing from the array, which is more general than getting the element at index 1, which can be fooled by curl --header "X-Forwarded-For: 1.2.3.4, 5.6.7.8" "https://example.com". Commented May 29, 2020 at 8:06
10

function getCallerIP(request) {
    var ip = request.headers['x-forwarded-for'] ||
        request.connection.remoteAddress ||
        request.socket.remoteAddress ||
        request.connection.socket.remoteAddress;
    ip = ip.split(',')[0];
    ip = ip.split(':').slice(-1); //in case the ip returned in a format: "::ffff:146.xxx.xxx.xxx"
    return ip;
}

2
  • 1
    You are right, if you want the ip as string, then you can replace the last line with: ip = ip.split(':').slice(-1)[0] Commented Sep 14, 2017 at 8:29
  • Code-only answers are discouraged. Can you explain how this answer is better than the older, better explained, and (much) more upvoted answers? Commented May 29, 2020 at 7:55
10

There are two ways to get the ip address :

  1. let ip = req.ip

  2. let ip = req.connection.remoteAddress;

But there is a problem with above approaches.

If you are running your app behind Nginx or any proxy, every single IP addresses will be 127.0.0.1.

So, the best solution to get the ip address of user is :-

let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
7

In node 10.14 , behind nginx, you can retrieve the ip by requesting it through nginx header like this:

proxy_set_header X-Real-IP $remote_addr;

Then in your app.js:

app.set('trust proxy', true);

After that, wherever you want it to appear:

var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;
6

If you're using express version 3.x or greater, you can use the trust proxy setting (http://expressjs.com/api.html#trust.proxy.options.table) and it will walk the chain of addresses in the x-forwarded-for header and put the latest ip in the chain that you've not configured as a trusted proxy into the ip property on the req object.

5

If you're using express.js then,

app.post('/get/ip/address', function (req, res) {
      res.send(req.ip);
})
5

var ipaddress = (req.headers['x-forwarded-for'] || 
req.connection.remoteAddress || 
req.socket.remoteAddress || 
req.connection.socket.remoteAddress).split(",")[0];

2
  • 3
    There are already well-received answers for this question. Why is this code sample better than them? Please add more of an explanation.
    – Tyler2P
    Commented Jun 22, 2021 at 15:49
  • its more comprehensive
    – user6221709
    Commented Aug 14, 2022 at 14:54
4

There were a lot of great points here but nothing that was comprehensive, so here's what I ended up using:

function getIP(req) {
  // req.connection is deprecated
  const conRemoteAddress = req.connection?.remoteAddress
  // req.socket is said to replace req.connection
  const sockRemoteAddress = req.socket?.remoteAddress
  // some platforms use x-real-ip
  const xRealIP = req.headers['x-real-ip']
  // most proxies use x-forwarded-for
  const xForwardedForIP = (() => {
    const xForwardedFor = req.headers['x-forwarded-for']
    if (xForwardedFor) {
      // The x-forwarded-for header can contain a comma-separated list of
      // IP's. Further, some are comma separated with spaces, so whitespace is trimmed.
      const ips = xForwardedFor.split(',').map(ip => ip.trim())
      return ips[0]
    }
  })()
  // prefer x-forwarded-for and fallback to the others
  return xForwardedForIP || xRealIP || sockRemoteAddress || conRemoteAddress
}
3

If you get multiple IPs , this works for me:

var ipaddress = (req.headers['x-forwarded-for'] || 
req.connection.remoteAddress || 
req.socket.remoteAddress || 
req.connection.socket.remoteAddress).split(",")[0];

3

Simple get remote ip in nodejs:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
0
3

req.connection has been deprecated since [email protected]. Using req.connection.remoteAddress to get the client IP might still work but is discouraged.

Luckily, req.socket.remoteAddress has been there since [email protected] and is a perfect replacement:

The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if the socket is destroyed (for example, if the client disconnected).

2

I realize this has been answered to death, but here's a modern ES6 version I wrote that follows airbnb-base eslint standards.

const getIpAddressFromRequest = (request) => {
  let ipAddr = request.connection.remoteAddress;

  if (request.headers && request.headers['x-forwarded-for']) {
    [ipAddr] = request.headers['x-forwarded-for'].split(',');
  }

  return ipAddr;
};

The X-Forwarded-For header may contain a comma-separated list of proxy IPs. The order is client,proxy1,proxy2,...,proxyN. In the real world, people implement proxies that may supply whatever they want in this header. If you are behind a load balancer or something, you can at least trust the first IP in the list is at least whatever proxy some request came through.

2

I use this for ipv4 format

req.connection.remoteAddress.split(':').slice(-1)[0]
2

You can Get User Ip with Express Like this

req.ip

For Example In This case we get the user Ip and send it back to the user With req.ip

app.get('/', (req, res)=> { 
    res.send({ ip : req.ip})
    
})
1
  • req.ip may also include an IPv4 subnet prefix ::ffff: - as explained in this answer. easy to filter out --> req.ip.toString().replace('::ffff:', '');
    – neonwatty
    Commented Oct 5, 2022 at 15:14
2

For me using kubernetes ingress (NGINX):

req.headers['x-original-forwarded-for']

Worked like a charm in Node.js

1
  • 1
    This worked. get the actual IP address behind the proxy. Commented Aug 10, 2023 at 10:28
1

If you are using Graphql-Yoga you can use the following function:

const getRequestIpAddress = (request) => {
    const requestIpAddress = request.request.headers['X-Forwarded-For'] || request.request.connection.remoteAddress
    if (!requestIpAddress) return null

    const ipv4 = new RegExp("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")

    const [ipAddress] = requestIpAddress.match(ipv4)

    return ipAddress
}

1

I'm using express behind nginx and

req.headers.origin

did the trick for me

1
  • This answer seems off. req.headers.orgin returns the IP address the client browser application was pointing to, not the IP of the client itself.
    – zipzit
    Commented Dec 28, 2021 at 19:56
1

If using express

const ip = req.ip?.replace(/^.*:/, '') //->192.168.0.101

or

const ip_raw = req.headers['x-forwarded-for'] ||
     req.socket.remoteAddress ||
     null; //->:ffff:192.168.0.101
const ip = ip_raw?.replace(/^.*:/, '')//->192.168.0.101

note: req.ip?.replace(/^.*:/, '')
            ^             ^
      null secure      regular expressin
    (if ip=!null continue to apply a regular expression)
1

Well, finaly my solution was IT DEPENDS ! For exampe if you have NGINX as a webserver look at you config for example:

server {
    listen 443 ssl;
    server_name <your-domain>;

    ssl_certificate /etc/letsencrypt/live/<your-domain>/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/<your-domain>/privkey.pem; # managed by Certbot
    
    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr; # THIS LINE !!!!
    }
}

so the focus is on $remote_addr => x-real-ip

so in nodejs only type req.headers["x-real-ip"]

and thats it !

1

So when you are using nodejs with express. you can you can simply use req.ip.split(":").pop(); to get client's ipv4 address as in the code below.

app.get("/ipv4", (req, res) => {

  const ipv4 = req.ip.split(":").pop();
  console.log("ipv4: ", ipv4);
  res
    .status(200)
    .send(
      `Hello, your ipv4 address is ${ipv4}`
    );
});

In the code above you are simply accessing ip value in the request object which looks something like (::ffff:127.0.0.1) then you are splitting the string by (:) and taking the last value which is the ipv4 part you need.

0
    const express = require('express')
    const app = express()
    const port = 3000

    app.get('/', (req, res) => {
    var ip = req.ip
    console.log(ip);
    res.send('Hello World!')
    })

   // Run as nodejs ip.js
    app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
    })
0

In a shell, you would just curl https://api.ipify.org

So, let's observe this to port it to node.js!

curl is a application to fetch data from websites, we pass the website "https://api.ipify.org" as the argument. We could use node-fetch to replace curl!

The data we get from the website is our IP address, It's some sort of thing which just fetches your IP.

So to sum it up:

const fetch = require('node-fetch');

fetch('https://api.ipify.org')
  .then(response => {/* whatever */})
  .catch(err => {/* whatever */})
3
  • 1
    I think you misunderstood the question. The OP does not want the server IP address, but the IP address of the connecting client
    – nuts
    Commented Mar 28, 2022 at 15:43
  • Oh, alright then! Sorry, I thought he wanted the server IP... Commented Jul 9, 2022 at 5:48
  • You can also use this with the browser's default fetch... So, my answer still stands! Commented Dec 5, 2022 at 12:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.