[zeromq-dev] IPC and free ports

andrea crotti andrea.crotti.0 at gmail.com
Thu Oct 11 18:14:12 CEST 2012


I have some problems on a test machine with tcp ports and binds
(probably just trying to bind twice), so since it's only one host anyway
I thought that I could also try IPC.


But I wanted to see how it works and I tried this:

import zmq


addr = 'ipc://local_proc'

ctx = zmq.Context()
sock1 = ctx.socket(zmq.REP)
sock2 = ctx.socket(zmq.REP)

sock1.bind(addr)
sock2.bind(addr)


Which to my surprise does not fail, while it does if I replace addr with:
    addr = 'tcp://127.0.0.1:5555'


So suppose I want to make sure that I'm not binding twice, what should I
do? Check if the file already exists or?


I also then created a function, that in theory should help me allocating
a new channel, that could be tcp with increasing port numbers, or named ipc:

def get_channel(name, tcp=False):
    """Return a channel, by default using IPC or tcp if requested.
    """
    # TODO: add a way to check if the channel is actually free, might
    # for example try to bind and catch a possible error
    if tcp:
        global NEXT_PORT
        channel = 'tcp://127.0.0.1:%d' % NEXT_PORT
        NEXT_PORT += 1
    else:
        # TODO: check that the file is there
        channel = 'ipc://%s' % name

    logger.debug("Generating channel %s" % channel)
    return channel


But the other problem, is how do I check that a tcp channel is usable?

One way would be simply

try:
     sock.bind(addr)
except zmq.Error:
    # loop over until find a free channel


Is this the easiest way to do this?

Thanks a lot,
Andrea



More information about the zeromq-dev mailing list