Mojolicious/Perl-从数据包获取IP? [英] Mojolicious / Perl - Getting IP from packet?

查看:85
本文介绍了Mojolicious/Perl-从数据包获取IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Perl'Mojolicious'框架编写了一个API,该API可以通过CORS接收来自其他Web服务器的请求,但是我在提取请求服务器的IP地址时遇到了麻烦.

提取诸如X-Forwarded-For之类的标头仅提供客户端的IP地址吗?在Perl或Mojolicious中有什么方法可以从IP数据包本身提取源IP?

使用内置的Mojolicious $self->tx->remote_address方法不起作用,因为我的API Web服务器位于Nginx反向代理后面.

解决方案

我使用自己的帮助器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;
});

在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;
    }

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.

解决方案

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;
    }

这篇关于Mojolicious/Perl-从数据包获取IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆