如何获取客户端的IP地址?

9 elixir phoenix-framework

我需要获取客户端的IP地址,这不起作用:

  def create(conn) do
    ip_address = conn.inet.ip_address
    # ....
Run Code Online (Sandbox Code Playgroud)

由于key :inet not found in: %Plug.Conn.我怎样才能获得IP地址呢?

小智 16

获得IP:

conn.remote_ip

从ip_address转换为字符串:

to_string(:inet_parse.ntoa(conn.remote_ip))

  • 铸造代码不是 Elixir :) 这是 Elixir 方式:`conn.remote_ip |> :inet_parse.ntoa |> to_string()` ;) (3认同)

The*_*Anh 10

检查此请求字段:

remote_ip - 客户端的IP,例如:{151,236,219,228}.该字段意味着被插入例如X-Forwarded-For标头或HAProxy的PROXY协议的插头覆盖.它默认为对等的IP.

这就是你要找的东西:

conn.remote_ip
Run Code Online (Sandbox Code Playgroud)

  • `conn.remote_ip |> Tuple.to_list |> Enum.join(".")`也可以.无需执行`Integer.to_string`调用. (6认同)
  • 上述示例仅适用于IPv4地址.如果您需要IPv4和IPv6的解决方案,请使用Erlang的inet的函数[ntoa](http://erlang.org/doc/man/inet.html#ntoa-1):`conn.remote_ip |>:inet. ntoa()|> to_string()` (4认同)