Connect to the first free port with TCP using 0MQ

I am writing a distributed search algorithm in which agents must listen on a TCP socket for incoming connections. At some point, the agent must bind a free TCP port. The port number is not important, but the agent must send its listening port number to other agents.

I think this is the correct way:

socket.bind("tcp://*:0"); 

Socket binds successfully, but then, how do I get the port number to which this socket is bound? I do not see the option code on the zmq_getsockopt man page returning the port number.

+4
source share
1 answer

With Zeromq, you use a string to bind or connect. It starts with protecol, tcp:// in your case, it's all right. Then you have a '*' which is for all available devices. Then you end with the port number :0 in your case.

 socket.bind("tcp://*:2424) 

Let's try to bind on port 2424. If you run man zmq_tcp, it will report a port number above 1024. In principle, you should know your port number in advance, and not after binding. In newer versions 3.2, you can also specify the port: 0 or: *, then os will decide where the port is. This can be obtained using socket.getsockopt (), as shown in the following example:

 zmq::context_t context(1); zmq::socket_t sock(context, ZMQ_REP); char port[1024]; //make this sufficiently large. //otherwise an error will be thrown because of invalid argument. size_t size = sizeof(port); try{ sock.bind("tcp://*:*"); } catch (zmq::error_t&e ){ cerr << "couldn't bind to socket: " << e.what(); return e.num(); } sock.getsockopt( ZMQ_LAST_ENDPOINT, &port, &size ); cout << "socket is bound at port " << port << endl; 

This will produce the following result, for example:

 socket is bound at port tcp://0.0.0:53269 

So, you still have to parse 53269 from the line "tcp: //0.0.0.0: 53269" hope this helps

+11
source

Source: https://habr.com/ru/post/1482236/


All Articles