Jak określić adres IP użytkownika w węźle

Jak mogę określić adres IP danego żądania z poziomu kontrolera? Na przykład (w wyrażeniu):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})
 393
Author: Jonas, 2011-11-12

21 answers

W twoim obiekcie request znajduje się właściwość o nazwie connection, która jest obiektem net.Socket. Sieć.Obiekt Socket ma właściwość remoteAddress, dlatego powinieneś być w stanie uzyskać adres IP za pomocą tego wywołania:

request.connection.remoteAddress

Zobacz dokumentację dla http i net

EDIT

Jak zaznacza @juand w komentarzach, poprawną metodą uzyskania zdalnego IP, jeśli serwer znajduje się za proxy, jest request.headers['x-forwarded-for']

 499
Author: topek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-28 03:15:46
var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     (req.connection.socket ? req.connection.socket.remoteAddress : null);

Zauważ, że czasami można uzyskać więcej niż jeden adres IP w req.headers['x-forwarded-for']. Ponadto, nagłówek x-forwarded-for nie zawsze będzie ustawiony, co może spowodować błąd.

Ogólny format pola to:

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

Gdzie wartość jest listą adresów IP rozdzieloną przecinkami i spacjami, z których najbardziej po lewej stronie znajduje się oryginalny klient, a każdy kolejny serwer proxy, który przeszedł żądanie, dodaje adres IP, z którego otrzymał żądanie. W tym przykładzie wniosek przekazany przez proxy1, proxy2, a potem proxy3. proxy3 pojawia się jako zdalny adres żądania.

Jest to rozwiązanie zaproponowane przez Arnav Gupta z fixem Martin zasugerował poniżej w komentarzach dla przypadków, gdy x-forwarded-for nie jest ustawione:

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

Sugestia przy użyciu nowoczesnego JS:

const parseIp = (req) =>
    (typeof req.headers['x-forwarded-for'] === 'string'
        && req.headers['x-forwarded-for'].split(',').shift())
    || req.connection?.remoteAddress
    || req.socket?.remoteAddress
    || req.connection?.socket?.remoteAddress

console.log(parseIp(req))
// => 127.0.0.1
 450
Author: Edmar Miyake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-14 13:57:04

Jeśli używasz express...

req.ip

Szukałem tego, a potem byłem jak czekaj, używam express. Duh.

 102
Author: Jason Sebring,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-26 20:33:15

Możesz pozostać na sucho i po prostu użyć node-ipware obsługuje zarówno IPv4 , jak i IPv6 .

Zainstaluj:

npm install ipware

W aplikacji.js lub 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();
});

Podejmie najlepszą próbę uzyskania adresu IP użytkownika lub zwrotu 127.0.0.1, aby wskazać, że nie może określić adresu IP użytkownika. Zobacz też README plik dla Opcji Zaawansowanych.

 34
Author: un33k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-03 21:11:36

Możesz użyć request-ip , Aby pobrać adres ip użytkownika. Obsługuje sporo różnych przypadków krawędzi, z których niektóre są wymienione w innych odpowiedziach.

Disclosure: stworzyłem ten moduł

Zainstaluj:

npm install request-ip

W aplikacji:

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

 22
Author: pbojinov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-09 20:44:05

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

Jeśli jest tam nagłówek x-forwarded-for, Użyj tego, w przeciwnym razie użyj właściwości .remoteAddress.

Nagłówek x-forwarded-for jest dodawany do żądań, które przechodzą przez Równoważniki obciążenia (lub inne typy proxy) skonfigurowane dla HTTP lub HTTPS (możliwe jest również dodanie tego nagłówka do żądań podczas balansowania na poziomie TCP przy użyciu protokołu proxy). Dzieje się tak dlatego, że request.connection.remoteAddress właściwość będzie zawierać prywatny adres IP load balancer, a nie publiczny adres IP klienta. Używając instrukcji lub, w powyższej kolejności sprawdzasz istnienie nagłówka x-forwarded-for i używasz go, jeśli istnieje, użyj request.connection.remoteAddress.

 19
Author: Ben Davies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-23 16:40:29

Poniższa funkcja ma wszystkie przypadki objęte pomoże

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);
 14
Author: ashishyadaveee11,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-08 08:25:47

Istnieją dwa sposoby uzyskania adresu ip:

  1. let ip = req.ip

  2. let ip = req.connection.remoteAddress;

Ale jest problem z powyższymi podejściami.

Jeśli używasz aplikacji za Nginx lub dowolnym proxy, każdy pojedynczy adres IP będzie 127.0.0.1.

Więc najlepszym rozwiązaniem, aby uzyskać adres ip użytkownika jest: -

let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
 9
Author: Mansi Teharia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-04 13:12:00

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;
}
 7
Author: Ahmad Agbaryah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-07 14:27:41

Jeśli używasz express w wersji 3.x lub większe, możesz użyć ustawienia trust proxy ( http://expressjs.com/api.html#trust.proxy.options.table ) i przejdzie przez łańcuch adresów w nagłówku X-forwarded-for i umieści najnowszy adres ip w łańcuchu, który nie został skonfigurowany jako zaufany serwer proxy, we właściwości ip obiektu req.

 6
Author: Michael Lang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-10 20:10:26

W node 10.14 , za nginx, możesz pobrać adres ip, żądając go przez nagłówek nginx w następujący sposób:

proxy_set_header X-Real-IP $remote_addr;

Następnie w aplikacji.js:

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

Po tym, gdzie chcesz, aby się pojawił:

var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;
 6
Author: Alexandru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-17 16:29:38

Ostrzeżenie:

Nie używaj tego na ślepo do ważnego ograniczenia szybkości:

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

To bardzo łatwe do sfałszowania:

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

W takim przypadku prawdziwy adres IP użytkownika będzie:

let ip = request.headers['x-forwarded-for'].split(',')[1];
Dziwię się, że żadne inne odpowiedzi o tym nie wspominały.
 6
Author: Community,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

Jeśli masz wiele IP, to działa dla mnie:

var ipaddress = (req.headers['x-forwarded-for'] || 
req.connection.remoteAddress || 
req.socket.remoteAddress || 
req.connection.socket.remoteAddress).split(",")[0];
 3
Author: Kirill Chatrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 15:28:10

Simple get remote ip in nodejs:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
 3
Author: IT Vlogs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-05 03:23:46

[[4]}Próbowałem wszystkie z nich nie działa choć,

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]);

Podczas uruchamiania aplikacji Express za proxy dla me nginx, musisz ustawić zmienną aplikacji trust proxy na true. Express oferuje kilka innych wartości trust proxy, które można przejrzeć w ich dokumentacji, ale poniższe kroki zadziałały dla mnie.

  1. app.Ustaw ('trust proxy', true) w aplikacji Express.

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

  1. Dodaj proxy_set_header X-Forwarded-dla $ remote_addr w Nginx konfiguracja dla Twojego bloku serwerowego.
  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. możesz teraz odczytać adres IP klienta z req.header ('X-forwarded-for') lub req.połączenie.remoteAddress; Pełny kod dla 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();
};
 3
Author: anik islam shojib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-22 15:37:51

Zdaję sobie sprawę, że odpowiedź na to była śmiertelna, ale oto nowoczesna wersja ES6, którą napisałem, która jest zgodna ze standardami Airbnb-base eslint.

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;
};

Nagłówek X-Forwarded - For może zawierać oddzieloną przecinkami listę adresów IP serwera proxy. Zamówienie to klient, proxy1, proxy2,..., proxyN. W prawdziwym świecie ludzie implementują proxy, które mogą dostarczać cokolwiek chcą w tym nagłówku. Jeśli jesteś za load balancer lub coś takiego, możesz przynajmniej zaufać pierwszy adres IP na liście jest przynajmniej cokolwiek proxy niektóre Prośba dotarła.

 2
Author: Misha Nasledov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-12 01:01:17

[[1]}używam express za nginx i

req.headers.origin

Did the trick for me

 2
Author: Matan Livne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-17 08:12:22

Jeśli używasz Graphql-Yoga możesz użyć następującej funkcji:

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
Author: Arsham Gh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-30 20:03:56
    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
Author: Devanand N Kulkarni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-12 07:34:49

req.connection został wycofany od [email protected] . Używanie req.connection.removeAddress, Aby uzyskać adres IP klienta, może nadal działać, ale nie jest zalecane.

Na szczęście, req.socket.remoteAddress jest tam od [email protected] i jest idealnym zamiennikiem:

Ciąg znaków zdalnego adresu IP. Na przykład, '74.125.127.100' lub '2001:4860:a005::68'. Wartość może być undefined, jeśli gniazdo jest zniszczone(na przykład, jeśli klient jest odłączony).

 0
Author: Nino Filiu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-27 23:30:21

Miał ten sam problem...im również nowy w javascript, ale rozwiązałem to z req.połączenie.remoteAddress; który dał mi adres IP (ale w formacie ipv6:: ffff.192.168.0.101), a następnie .wycinek , aby usunąć 7 pierwszych cyfr.

var ip = req.connection.remoteAddress;

if (ip.length < 15) 
{   
   ip = ip;
}
else
{
   var nyIP = ip.slice(7);
   ip = nyIP;
}
 -8
Author: aCo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-11 20:56:24