sockets - 获取一个随机的、仍然可用的高端口号

标签 sockets posix tcp

假设我想在 IPC 的某个端口上运行 TCP/IP 服务。当我将端口号传递给我想与之通信的进程时,端口号并不重要。获取系统仍然可用的随机高(通常> 49152)端口号的最佳方法是什么? POSIX 中有什么我可以使用的吗?

我知道 FTP 服务器经常需要这个。

最佳答案

如果您不指定端口号,操作系统将自动选择 ephemeral port给你号码。

来自 Choosing the Port Number :

New server software should strive to avoid depending on a specific port number, especially if it is user-level software that is not ineluctably tied to a well-known port. Fortunately, this is easily done by requesting port 0, which instructs the system to choose an ephemeral port number.

关于sockets - 获取一个随机的、仍然可用的高端口号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/948122/

相关文章:

linux - 判断socket上是否还有Data残留并丢弃

linux - 在 Linux 或 POSIX 环境中是否有 Microsoft 的 UuidCompare、UuidCreate 等等效项?

c - 为什么 _SC_AIO_MAX 定义明确,而 sysconf(_SC_AIO_MAX) 返回 -1?

delphi - Indy TCPClient 和 InputBuffer 中的流氓字节

python - 0x8915有什么用?

node.js - NodeJS - 我的应用程序无法启动

c++ - Linux 中的套接字——我怎么知道客户端已经完成?

c++ - 输出到 stdout/cout/etc 的进程间同步

algorithm - 返回 N 窗口大小

scala - Akka 关闭 TCP actor