Reputation: 4143
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/receive 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:
Also a code sample of the setup of such socket would be welcome, as well as an example of sending/receiving character strings.
Upvotes: 14
Views: 20835
Reputation: 22238
Answer by Remy Lebeau is good if you need a temporary port. It is not so good if you need a persistent reserved port because other software also uses the same method to get a port (including OS TCP stack that needs a new temporary port for each connection).
So the following might happen:
Then you need to e.g. restart the software:
So for "future uses" you need a port that is not in ephemeral port range (that's the range from which bind(host, 0) returns a port).
My solution for this issue is the port-for command-line utility.
Upvotes: 1
Reputation: 7203
If it being a random port is actually important, you should do something like:
srand(time(NULL));
rand() % NUM_PORTS; // NUM_PORTS isn't a system #define
Then specify that port in bind. If it fails, pick a new one (no need to re-seed the random generator. If the random port isn't important, look at Remy Lebeau's answer.
Upvotes: 0
Reputation: 595887
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.
Upvotes: 28