How to decide if a file descriptor is attached to a file or socket in Linux?

Using C in Linux, how to decide if a file descriptor is attached to a file or socket?

+4
source share
3 answers

Use getsockoptto get SO_TYPEto file descriptor. If this is not a socket, it will return -1with an error 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 */
+7
source

Alternatively, you can use the macro fstatand S_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);
}
+6
source

(7) :

pread (2) pwrite (2) .

So another option is to perform one of these unsupported operations and see if you have an error. If you managed to find, then FD is probably a file (or device). Otherwise, it could be a socket. Or a pipe.

0
source

All Articles