refactor: move ntoa (ip address formatting) code to emqx_utils

This commit is contained in:
Zaiming (Stone) Shi 2023-12-17 19:51:56 +01:00
parent 363c56c085
commit 35504bd323
3 changed files with 17 additions and 8 deletions

View File

@ -61,10 +61,8 @@ kmg(Byte) ->
kmg(F, S) -> kmg(F, S) ->
iolist_to_binary(io_lib:format("~.2f~ts", [F, S])). iolist_to_binary(io_lib:format("~.2f~ts", [F, S])).
ntoa({0, 0, 0, 0, 0, 16#ffff, AB, CD}) -> ntoa(Ip) ->
inet_parse:ntoa({AB bsr 8, AB rem 256, CD bsr 8, CD rem 256}); emqx_utils:ntoa(Ip).
ntoa(IP) ->
inet_parse:ntoa(IP).
merge_maps(Default, New) -> merge_maps(Default, New) ->
maps:fold( maps:fold(

View File

@ -1039,9 +1039,10 @@ reason({shutdown, Reason}) when is_atom(Reason) -> Reason;
reason({Error, _}) when is_atom(Error) -> Error; reason({Error, _}) when is_atom(Error) -> Error;
reason(_) -> internal_error. reason(_) -> internal_error.
ntoa(undefined) -> undefined; ntoa(undefined) ->
ntoa({IpAddr, Port}) -> iolist_to_binary([inet:ntoa(IpAddr), ":", integer_to_list(Port)]); undefined;
ntoa(IpAddr) -> iolist_to_binary(inet:ntoa(IpAddr)). ntoa(IpOrIpPort) ->
iolist_to_binary(emqx_utils:ntoa(IpOrIpPort)).
event_name(?BRIDGE_HOOKPOINT(_) = Bridge) -> Bridge; event_name(?BRIDGE_HOOKPOINT(_) = Bridge) -> Bridge;
event_name(<<"$events/client_connected">>) -> 'client.connected'; event_name(<<"$events/client_connected">>) -> 'client.connected';

View File

@ -64,7 +64,8 @@
tcp_keepalive_opts/4, tcp_keepalive_opts/4,
format/1, format/1,
format_mfal/1, format_mfal/1,
call_first_defined/1 call_first_defined/1,
ntoa/1
]). ]).
-export([ -export([
@ -1031,6 +1032,15 @@ flatcomb(Ys = [_ | _], Zs = [_ | _]) ->
flatcomb(Y, Zs) -> flatcomb(Y, Zs) ->
[Y | Zs]. [Y | Zs].
%% @doc Format IP address tuple or {IP, Port} tuple to string.
ntoa({IP, Port}) ->
ntoa(IP) ++ ":" ++ integer_to_list(Port);
ntoa({0, 0, 0, 0, 0, 16#ffff, AB, CD}) ->
%% v6 piggyback v4
inet_parse:ntoa({AB bsr 8, AB rem 256, CD bsr 8, CD rem 256});
ntoa(IP) ->
inet_parse:ntoa(IP).
-ifdef(TEST). -ifdef(TEST).
-include_lib("eunit/include/eunit.hrl"). -include_lib("eunit/include/eunit.hrl").