问题
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