Search code examples
clinuxsocketstcplibuv

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


The POSIX accept function returns the descriptor for the socket that has been accepted. However uv_accept returns an error indicator instead.

How to get the file descriptor then?


Solution

  • The question can be slightly reformulated as:

    Extracting the file descriptor out of a handle

    Ironically, that is the title of a section of the migration guide to libuv 1.0 (see here for further details).

    Before version 1.0, the not recommend way to do that was accessing the internals of the library as it follows:

    handle->io_watcher.fd
    

    Since libuv v1.0, the recommend way is using uv_fileno instead.
    The documentation states that:

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

    Therefore, it depends on what version of libuv you are using which is the best way to get it out of a handle.