gpt4 book ai didi

elixir - 如何在 Phoenix rest api 中获取客户端 IP

转载 作者:行者123 更新时间:2023-12-03 17:39:48 25 4
gpt4 key购买 nike

我在 Elixir Phoenix 中有 rest API,我想记录每个请求者客户端 IP。目前,我正在使用以下代码来获取客户端 IP:

conn.remote_ip |> Tuple.to_list |> Enum.join(".")

但是,它给了我本地 IP 127.0.0.1 .

然后,我使用了以下代码:
remote_ips = Plug.Conn.get_req_header(conn, "x-forwarded-for")
remote_ip = List.first(remote_ips)

它给了零 x-forwarded-for .

请帮我解决这个问题。

最佳答案

上述解决方案有效,但我也遇到了这个问题,我发现了非常复杂的解决方案,但是我检查了 Plausible Analytics已经做到了,就在这里。
来自 Plausible Analytics 的源代码:

defmodule MyAppWeb.RemoteIp do
def get(conn) do
forwarded_for = List.first(Plug.Conn.get_req_header(conn, "x-forwarded-for"))

if forwarded_for do
String.split(forwarded_for, ",")
|> Enum.map(&String.trim/1)
|> List.first()
else
to_string(:inet_parse.ntoa(conn.remote_ip))
end
end
end

关于elixir - 如何在 Phoenix rest api 中获取客户端 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39199899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com