문제

From the erlang reference for the peername function it shows there are two possible returns. One is the ip-address and port while the other is an error. The question I have is how would I create a case statement which checks both in case there is an error?

So far I have this code which only works if the function actually returns something useful, but what happens to the tuple if theres an error?

ip_address(Socket) ->   
    {ok,{Ip,Port}} = inet:peername(Socket),
도움이 되었습니까?

해결책

like that:

ip_address(Socket) ->
    case inet:peername(Socket) of
        {ok, {Ip, Port}} ->
            io:format("ip ~p, port ~p~n", [Ip, Port]);
        {error, Error} ->
            io:format("error ~p~n", [Error])
    end.

or you can use another function with two clauses:

ip_address(Socket) ->
    ip_address_1(inet:peername(Socket)).

ip_address_1({ok, {Ip, Port}}) ->
    io:format("ip ~p, port ~p~n", [Ip, Port]);
ip_address_1({error, Error}) ->
    io:format("error ~p~n", [Error]).
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top