简体   繁体   中英

Retrieve client IP in :ranch

I'm using :ranch to receive TCP packges in my Phoenix application.

First I created a listener in the server using:

:ranch.start_listener(tcp_echo, ranch_tcp, [{port, 5555}], echo_protocol, [] )

How could I print the client IP in the echo_protocol ?

Ranch includes a sample echo application .

In echo_protocol.erl , there's an init function that accepts the connection from the client:

init(Ref, Socket, Transport, _Opts = []) ->
    ok = ranch:accept_ack(Ref),
    loop(Socket, Transport).

You can display the client ip address there:

init(Ref, Socket, Transport, _Opts = []) ->
    ok = ranch:accept_ack(Ref),
    {ok, {IpAddress, _}} = inet:peername(Socket),
    io:format("Client ~p~n", [IpAddress]),
    loop(Socket, Transport).

It will appear in a format like:

Client {127,0,0,1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM