如何确定文件描述符是否附加到Linux中的文件或套接字

Ran*_*Tek 4 c unix sockets linux posix

在Linux中使用C语言,如何确定文件描述符是否附加到文件或套接字?

ick*_*fay 7

使用getsockopt得到SO_TYPE的文件描述符.如果它不是套接字,它将返回-1错误ENOTSOCK:

int fd = /* ... */;
bool is_socket;
int socket_type;
socklen_t length = sizeof(socket_type);

if(getsockopt(fd, SOL_SOCKET, SO_TYPE, &socket_type, &length) != -1) {
    is_socket = true;
} else {
    if(errno == ENOTSOCK) {
        is_socket = false;
    } else {
        abort();  /* genuine error */
    }
}

/* whether it is a socket will be stored in is_socket */
Run Code Online (Sandbox Code Playgroud)


Duc*_*uck 7

或者,您可以使用fstatS_ISSOCK宏.

int main(int argc, char *argv[])
{
    int fds[2];

    fds[0] = 0; //stdin
    fds[1] = socket(AF_INET,SOCK_STREAM, 0);

    for (int i = 0; i < 2; ++i)
    {
        struct stat statbuf;

        if (fstat(fds[i], &statbuf) == -1)
        {
            perror("fstat");
            exit(1);
        }

        if (S_ISSOCK(statbuf.st_mode))
            printf("%d is a socket\n", fds[i]);
        else
            printf("%d is NOT a socket\n", fds[i]);
    }

    return(0);
}
Run Code Online (Sandbox Code Playgroud)