Using C language in Linux, how to decide if a file descriptor is attached to a file or socket?
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 */
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With