如何在 Aqueduct Dart 服务器中获取客户端请求的 IP 地址

How to get the IP address of a client request in an Aqueduct Dart server

我正在制作 Aqueduct 服务器。我想知道用于监视日志和提供基于一般位置的内容的客户端请求的 IP 地址。

在 Aqueduct 中,我看不到如何获取 IP 地址。

我本来想说我尝试了 X、Y 和 Z 但没有用,但我刚刚找到答案所以我会在下面添加它。

在您的控制器中,您可以从 Request.

获取 IP 地址
String ipAddress = request.connectionInfo.remoteAddress.address;

请注意,如果您的服务器 运行 在 nginx 代理后面,那么您将必须配置 nxinx 以将真实 IP 转发到 Aqueduct。为此,您可以将带有远程地址的 X-Real-IP header 添加到服务器块中的代理 API 位置。

location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://127.0.0.1:8888;
    proxy_http_version 1.1;
}

然后在 Aqueduct 中,您可以从原始 headers:

中获取 IP 地址
String ipAddress = request.raw.headers['x-real-ip'].first;

更多信息在这里: