Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random port for UDP socket

Tags:

c

sockets

I need to create a program that will communicate with other programs on the same computer via UDP sockets. It will read commands from stdin, and some of this commands will make it to send/recieve packets without halting execution. I've read some information out there, but since I'm not familiar with socket programming and need to get this done quickly, I have the following questions:

  1. I need to get a random unused port for the program to listen to, and reserve it so other programs can communicate with this and also the port isn't reserved by another program. I also need to store the port number on a variable for future usage.
  2. Since the communication is across processes on the same machine, I'm wondering if I can use PF_LOCAL.

Also a code sample of the setup of such socket would be welcome, as well as an example of sending/recieving character strings.

like image 295
rabusmar Avatar asked Jan 12 '12 21:01

rabusmar


1 Answers

Call bind() specifying port 0. That will allow the OS to pick an unused port. You can then use getsockname() to retreive the chosen port.

like image 165
Remy Lebeau Avatar answered Oct 04 '22 04:10

Remy Lebeau