Get random port for UDP socket

前端 未结 3 873
旧时难觅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.

提交回复
热议问题