How to get the IP address and port number of the client and server in Node.js

I tried to find a lot to find a way to find out the client and server IP address and port number. So far I have discovered:

  • Client ip : may be known req.ip.
  • Client port . I searched a lot, but did not find a way to find this ephemeral client port. After checking the objects req, resI found that sometimes it res.connection._peernamecontains the client's IP address and port number. But this is not a reliable way to find the port number, because in some request this property is missing. So what is the right way to find out about a port?
  • Server ip . Here I am interested to know the external or public ip for the server. I searched a bit for the same thing and found this link that uses an external external api to retrieve an external ip. Is this the only possible way to find the external IP address? Or is there another way?
  • Server port . It can be recognized using listener.address().port [source] . But is it possible to learn from objects reqor res? In fact, I want to know the port number from middleware, where there is only req, resand next(basically app.use(function(req,res,next){...}))).
+4
source share
1 answer

, ( -):

req.connection.remoteAddress
req.connection.remotePort
req.connection.localAddress
req.connection.localPort

node.js net.js: https://github.com/nodejs/node/blob/863952ebadd4909a66bb9da7868bf75bbbe1462d/lib/net.js#L608

. , . .


, , .. , , , IP-, , IP- - HTTP ( IP, , - -), TCP- .

, -, HTTP:

X-Forwarded-For - The IP address of the client before it went through the proxy
X-Forwarded-Port - The port of the client before it went through the proxy

X-Forwarded , , , :

X-Forwarded-For: OriginatingClientIPAddress, proxy1-IPAddress, proxy2-IPAddress

RFC 7239 2014:

Forwarded: for=192.0.2.60; proto=http; by=203.0.113.43
+6

Source: https://habr.com/ru/post/1648159/


All Articles