Mojolicious / Perl - Getting IP from packet?

China☆狼群 提交于 2020-05-31 22:34:30

问题


I've written an API using the Perl 'Mojolicious' framework that recieves requests from other web servers via CORS, however I'm having trouble extracting the IP address of the requesting server.

Extracting headers like X-Forwarded-For only gives the IP address of the client? Is there any way in Perl or Mojolicious to extract the source IP from the IP packet itself?

Using the inbuilt Mojolicious $self->tx->remote_address method doesn't work because my API web server sits behind an Nginx reverse proxy.


回答1:


I use own helper src_addr:

use Net::IP::Lite;

$app->helper( src_addr => sub {
  my $c = shift;
  my $xff = $c->req->headers->header('X-Real-IP') // $c->req->headers->header('X-Forwarded-For') // '';

  if($xff) {
    for my $ip (reverse split(/[\s,]+/, $xff)) {
      next if ! ip_validate($ip);
      return $ip;
    }
  }
  return $c->tx->remote_address;
});

In nginx:

    location / {
            proxy_read_timeout 300;
            proxy_pass http://localhost4:54329/;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto "https";
            proxy_set_header X-Forwarded-HTTPS 1;
    }


来源:https://stackoverflow.com/questions/35312054/mojolicious-perl-getting-ip-from-packet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!