I have rest API in Elixir Phoenix and I want to log every requester client IP. Currently, I am using following code to get client IP:
conn.remote_ip |> Tuple.to_list |> Enum.join(".")
But, it gave me local IP 127.0.0.1
.
Then, I used following code:
remote_ips = Plug.Conn.get_req_header(conn, "x-forwarded-for")
remote_ip = List.first(remote_ips)
And it gave nil x-forwarded-for
.
Please help me to solve this issue.
Above solution works but I also had that problem and I found very complex solutions however I checked how Plausible Analytics had done it and here it is.
Source code from 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With