Skip to content

Instantly share code, notes, and snippets.

@brb
Created September 25, 2012 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brb/3782397 to your computer and use it in GitHub Desktop.
Save brb/3782397 to your computer and use it in GitHub Desktop.
Erlang PID by inet PORT
%% @doc Return pid of a process which opened a socket binded to a given port.
-spec get_pid(inet:port_number(), 'tcp' | 'udp' | 'sctp') -> pid() | undefined.
get_pid(Port, Proto) when is_integer(Port), is_atom(Proto) ->
Name = name(Proto),
InetPorts = [P || P <- erlang:ports(),
{name, Name} == erlang:port_info(P, name)],
try
lists:filter(
fun (P) ->
case inet:port(P) of
{ok, Port} -> throw({found, P});
_ -> ok
end
end,
InetPorts
),
undefined
catch
throw:{found, P} ->
proplists:get_value(connected, erlang:port_info(P))
end.
name(tcp) -> "tcp_inet";
name(udp) -> "udp_inet";
name(sctp) -> "sctp_inet".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment