Matthias Wandel
Matthias Wandel

Reputation: 6493

How to find a locally available UDP port with unix Sockets API

I have an application where I have potentially many processes must send a message to one process. I figured the most expedient way to do this would be to just send a UDP datagram.

When opening a socket, I need to specify which port to listen to. As I just want to fire and forget the UDP datagram, I'd like to just have the OS pick an available port. I'd rather not have to hunt for one, especially as many instances of my process may be running. Is there a way I can tell the OS to just pick an available port (or better yet, not even open a listening socket) to fire and forget my UDP datagram?

Upvotes: 1

Views: 2171

Answers (2)

Jerub
Jerub

Reputation: 42638

Yes. Specify 0 as the port. The OS will pick an available port for you.

Upvotes: 3

Tom Leys
Tom Leys

Reputation: 19029

Answering the "Problem" rather than the "Question"

If all the processes are operating on the same PC, you might want to look into shared files or some other means of communications other than a networking stack.

I'd suggest you explore the options in Boost's Interprocess library http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html

Quick guide here: http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/quick_guide.html

Specifically, I suggest you use a named pipe or shared memory between your processes.

Upvotes: 0

Related Questions