erlangerlang-ports

How to get an Erlang port by its ID?


When I have an Erlang process ID, using pid/3 or list_to_pid/1 functions (which internally do the same thing) I can get the process for debugging purposes.

Process = pid(0,4,1).
Process = list_to_pid("<0.4.1>").

So the question is; what about ports?

There are lots of function interfaces which accept both process() and port() data types, like register/2. So I need to know if there is a way to get ports by their ID (e.g. #Port<0.567>) like processes. Is it prohibited? If so, is there any reason for it?


Solution

  • I'm not aware of anything in the standard library to help with this, but there is the recon_lib:term_to_port/1 function in the recon library that does what you want. For example:

    1> {ok,L} = gen_tcp:listen(0, []).
    {ok,#Port<0.687>}
    2> L = recon_lib:term_to_port("#Port<0.687>").
    #Port<0.687>
    

    This code opens a listen socket on an ephemeral port and stores it in variable L. It then asserts, using pattern matching, that the result of passing the stringified port #Port<0.687> to recon_lib:term_to_port/1 returns exactly the same socket as L.