[zeromq-dev] automatically choosing a free TCP port

David Robinson zxvdr.au at gmail.com
Mon Mar 15 13:23:57 CET 2010

Hi Martin,

On Mon, Mar 15, 2010 at 10:52 PM, Martin Sustrik <sustrik at 250bpm.com> wrote:
> Hi David,
>> I'm looking at using avahi (eg, zeroconf) with a zeromq based
>> application. I'd like to be able to have zeromq bind to any free port
>> so that I can announce the service via avahi, but afaict the string
>> passed to zmq_bind must have a port number. Is there any way to avoid
>> specifying a TCP port number and just have one automatically assigned?
>> Apparently you can "just create the socket and call listen() on it.
>> Then, the IP stack will automatically assign a free port number. Use
>> getsockname() to query the port number that has been chosen and use
>> that when registering the Avahi service."  I tried using an address
>> string of "tcp://lo" without success (eg, zmq_bind (socket,
>> "tcp://lo")).
> No, the feature was deliberately omitted. The idea is that you can connect
> even to services that are not running (connecting side tries to reconnect
> automatically and queues the messages in the meantime). In that case there's
> no application that could ask kernel to assign a port number. For that
> reason we stick with fixed port numbers.

I'm not sure that I explained it very well. Automatically getting a
port would only make sense on the receive side of the connection
(obviously you can't send to a socket if you don't know what port to
send to).

> I am not familiar with avahi details. What's the use case and how would you
> except the whole thing to work?

The basic use-case would be to announce a service(s) to a network. eg,
you have an application that consumes something (using zmq_sub or
zmq_rep) and you don't want to have to tell all the clients how to
connect to it (eg, the IP address and port number that your zmq based
app is listening on - the address argument for zmq_bind). You can use
avahi to tell everything on the network what IP and port your
application is listening on. The publishing application(s) can then
feed your consumer because they learned the address details.

Its basically makes configuration a bit more flexible because you
don't have to care where your app runs - as long as everything that
needs to find it can find it you're happy. Avahi will make sure that
your producers can find your consumers (provided that you've hooked
them up correctly).


More information about the zeromq-dev mailing list