Get random port for UDP socket

前端 未结 3 874
旧时难觅i
旧时难觅i 2021-01-02 00:49

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 m

相关标签:
3条回答
  • 2021-01-02 01:15

    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:

    1. You call bind with 0 and getsockname() to get a port;
    2. then save it into config (or into several configs) for future uses;
    3. software that needs this port starts and binds the port.

    Then you need to e.g. restart the software:

    1. software stops and unbinds the port: the port can now be returned by bind(0) and getsockname() again;
    2. e.g. TCP stack needs a port and binds your port;
    3. software can't start because port is already bound.

    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.

    0 讨论(0)
  • 2021-01-02 01:26

    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.

    0 讨论(0)
  • 2021-01-02 01:27

    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.

    0 讨论(0)
提交回复
热议问题