user2805872 user2805872 - 3 months ago 47x
Node.js Question

How to retrieve client and server IP address and port number in Node.js

I tried to search a lot to find a way to know the client and server ip address and port number. So far I found:

  1. Client ip : can be known by

  2. Client port : I searched a lot but I couldn't find any way to find this client ephemeral port. After inspecting the
    objects, I found that sometimes
    contains the client ip address and port number. But this is not the reliable way to find the port number because in some request this property is missing. So, what is the correct way to know about the port ?

  3. Server ip : Here I am interested in knowing the external or public ip for the server. I searched a bit for the same and I found this link which uses some external api to retrieve the external ip. Is it the only possible way to find the external IP ? Or are there any other way possible ?

  4. Server port : It can be known with
    [source] . But can it be known from
    objects ? Actually I want to know the port number from within the middleware where I have
    only( basically


You can get those four values with these properties if you have a direct connection with the client (no proxies in the way):


Relevant node.js source code pointer in net.js:

Note: While you access these as property values, they are technically implemented as getters. You cannot set these properties.

If there is server infrastructure such as load balancers, proxies, etc... in front of your actual server, the above local values may return the local server, not what the actual public IP/port that the client originally connected to. The only way to retrieve the original public IP/port would be if your infrastructure sets the originals as a HTTP headers (which some proxies set IP, don't know if any proxies set port) since they are not present in the current raw TCP connection from the proxy.

For cases where a proxy is involved, you may also want to look at some HTTP headers:

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

The X-Forwarded headers may also be a comma separated list if it has gone through multiple proxies such as:

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

There is also a standard header as of RFC 7239 2014:

Forwarded: for=; proto=http; by=