What's the proper way to retrieve the client's IP address?

393 views
Skip to first unread message

Alexander Karelas

unread,
Jul 12, 2014, 3:46:53 PM7/12/14
to mojol...@googlegroups.com
I know there's $self->tx->remote_address, but that retrieves the address
of the reverse proxy (127.0.0.1).

Because even though I have set up a X-Real-IP header and a
X-Forwarded-For header, neither of these headers get used by
$self->tx->remote_address.

What's the right way to retrieve the client's IP address?

Luc Didry

unread,
Jul 12, 2014, 3:59:12 PM7/12/14
to mojol...@googlegroups.com
In your case, that's $c->req->headers->header('X-Forwarded-For');
--
Luc
http://www.fiat-tux.fr/
Internet n'est pas compliqué, Internet est ce que vous en faites.

signature.asc

Alexander Karelas

unread,
Jul 12, 2014, 7:34:14 PM7/12/14
to mojol...@googlegroups.com
I think that contains a comma-separated list of IP addresses, whereas
the X-Real-IP header always contains just one address.

- Alex
Message has been deleted

Jan Henning Thorsen

unread,
Jul 14, 2014, 6:02:06 AM7/14/14
to mojol...@googlegroups.com
Try setting { hypntoad => { proxy => 1, listen => [...] } in the config file, if you are using hypnotoad, or set the MOJO_REVERSE_PROXY=1 environment variable in other cases. Support for the environment variable was added in Mojolicious 5.11.

This will allow retrieving the IP address using $self->tx->remote_address

Юрий Корик

unread,
Jul 23, 2014, 7:17:54 AM7/23/14
to mojol...@googlegroups.com
What's the right way to retrieve the client's IP address? 

Create helper:

    $self->renderer->add_helper(ip => sub {
      my $self = shift;
      my $for  = $self->req->headers->header('X-Forwarded-For');
      return $for && $for !~ /unknown/i ? $for : undef || $self->req->headers->header('X-Real-IP') || $self->tx->{remote_address};
    });

Jan Henning Thorsen

unread,
Jul 23, 2014, 7:35:47 AM7/23/14
to mojol...@googlegroups.com
If you have set up the reverse proxy correct, you can just do $c->remote_address;

No idea why you want to look into the tx hash. You should always use the methods.

Look here: (there's also cookbooks for other servers on that page)

Also remember to set the MOJO_REVERSE_PROXY=1 environmnt variable as I said earlier in this thread.

Alexander Karelas

unread,
Jul 23, 2014, 8:41:10 AM7/23/14
to mojol...@googlegroups.com
That worked. Thank you.

- Alex
Reply all
Reply to author
Forward
0 new messages