Where does $remote_addr come from?

Francis Daly francis at daoine.org
Fri Feb 3 21:13:26 UTC 2017

On Fri, Feb 03, 2017 at 03:36:53PM -0500, Paul Nickerson wrote:

Hi there,

> > Exactly, it is what the source code says:
> >     v->data = r->connection->addr_text.data;
> > and then you can track where that addr_text.data value is set.
> I thought it might be coming from addr_text in the code, but my experience
> with C is dated and limited. I wasn't able to figure out where
> addr_text.data is set.

I have the 1.11.5 source easily to hand, so this is based on that.

$ grep -r addr_text.data . | wc -l

The first few of those are in ./src/event/ngx_event_accept.c, which
includes a call to ngx_pnalloc, which is probably related to alloc'ing
storage for some content.

Reading that file, the next likely looking line is:

            c->addr_text.len = ngx_sock_ntop(c->sockaddr, c->socklen,
                                             ls->addr_text_max_len, 0);

where the ".len" is the function return value, and ".data" is an address
passed in as an argument.

How is that function defined?

$  grep -r ngx_sock_ntop . | grep h:
./src/core/ngx_inet.h:size_t ngx_sock_ntop(struct sockaddr *sa, socklen_t socklen, u_char *text,

It's declared in ./src/core/ngx_inet.h; there's a good chance that it
is defined in ./src/core/ngx_inet.c, so look there.

It shows that the third argument is "u_char *text"; and for an IPv4
connection there are lines like

        p = (u_char *) &sin->sin_addr;
        p = ngx_snprintf(text, len, "%ud.%ud.%ud.%ud",
                             p[0], p[1], p[2], p[3]);

For an IPv6 connection or a unix domain socket connection, there are
other ngx_snprintf or (after another function call) ngx_sprintf calls
that write appropriate things to "text".

So addr_text.data is "whatever the other end of this connection is",
with the caveat that the realip module can be explicitly configured to
change what that appears to be.

(And therefore, any module *could* change what that appears to be. So
don't run modules you don't trust, if you want to be able to believe
what your nginx reports its internal state to be.)


Francis Daly        francis at daoine.org

More information about the nginx mailing list