how to get remote_ip from socket in phoenix-framework?

China☆狼群 提交于 2019-12-10 14:10:04

问题


How to get remote_ip from socket in phoenixframework? I can get it from conn in View, but not in Channel.

Many thanks for help!


回答1:


The answer right now is: you can't. You can't access the connection in channels because channels are transport agnostic. Open up an issue in Phoenix detailing your user case so the Phoenix team can act on it.




回答2:


Copy of the answer provided here: https://elixirforum.com/t/phoenix-socket-channels-security-ip-identification/1463/3 (all the credit goes to https://elixirforum.com/u/arjan)

Phoenix 1.4 update:

Since Phoenix 1.4, you can get connection information from the underlying transport. What kind of information you get is transport dependent, but with the WebSocket transport it is possible to retrieve the peer info (ip address) and a list of x- headers (for x-forwarded-for resolving).

Configure your socket like this in your endpoint.ex:

socket("/socket", MyApp.Web.UserSocket,
  websocket: [connect_info: [:peer_data, :x_headers]],
  longpoll: [connect_info: [:peer_data, :x_headers]]
)

And then your UserSocket module must expose a connect/3 function like this:

def connect(_params, socket, connect_info) do
  {:ok, socket}
end

On connect, the connect_info parameter now contains info from the transport:

info: %{
  peer_data: %{address: {127, 0, 0, 1}, port: 52372, ssl_cert: nil},
  x_headers: []
}


来源:https://stackoverflow.com/questions/33276202/how-to-get-remote-ip-from-socket-in-phoenix-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!