Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client IP in Phoenix rest api

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.

like image 244
azharmalik3 Avatar asked Nov 19 '22 20:11

azharmalik3


1 Answers

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
like image 63
nesimtunc Avatar answered Nov 22 '22 10:11

nesimtunc