如何在 libuv 中获取已接受的 tcp 套接字的文件描述符?

How to get file descriptor for an accepted tcp socket in libuv?

POSIX accept function returns the descriptor for the socket that has been accepted. However uv_accept returns 错误指示符。

那么如何获取文件描述符呢?

您可以在客户端 uv_stream 上使用 uv_fileno 功能。

在 Linux 和 Darwin 上,返回的 uv_os_fd_tint 的别名,因此您可以执行以下操作:

uv_tcp_t *client;
int conn_s;

// ...

uv_accept(server, (uv_stream_t*) client);
uv_fileno((uv_handle_t *)client, &conn_s);
printf("%d", conn_s);

问题可以稍微改写为:

Extracting the file descriptor out of a handle

具有讽刺意味的是,这是 libuv 1.0 迁移指南的一部分的标题(有关详细信息,请参阅 here)。

在 1.0 版之前,不推荐的方法是访问库的内部结构,如下所示:

handle->io_watcher.fd

从 libuv v1.0 开始,推荐的方法是使用 uv_fileno
文档指出:

Gets the platform dependent file descriptor equivalent.
The following handles are supported: TCP, pipes, TTY, UDP and poll. [...]

因此,这取决于您使用的 libuv 版本,哪种版本是从句柄中获取它的最佳方法。