Created
September 25, 2012 14:50
-
-
Save brb/3782397 to your computer and use it in GitHub Desktop.
Erlang PID by inet PORT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% @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