Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 747
RandyTek Avatar asked Dec 09 '22 11:12

RandyTek


2 Answers

Use getsockopt to get SO_TYPE on the file descriptor. If it is not a socket, it will return -1 with the 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 */
like image 198
icktoofay Avatar answered Dec 11 '22 09:12

icktoofay


Alternatively, you can use fstat and the S_ISSOCK macro.

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);
}
like image 27
Duck Avatar answered Dec 11 '22 08:12

Duck