3

When socket programming in C, I noticed that sometimes fcntl() is used to manipulate socket behavior while other times setsockopt() is used.

For example, fcntl() is used to make a socket non-blocking, but setsockopt() is used to change the timeout time when sending/receiving data from a socket.

Is there any background / intuitive reasoning as to why both functions are needed?

Izzo
  • 4,461
  • 13
  • 45
  • 82
  • 3
    `fcntl()` manipulates file descriptors, while `setsockopt()` manipulates socket-descriptors. Under Unix-style OS's, the two types of descriptor are mostly interchangeable, but under other OS's (read: Windows) file descriptors and socket-descriptors are different/incompatible types of object which therefore require different APIs to handle. (You could ask a similar question and get a similar line of reasoning re: `send()/recv()` vs `read()/write`) – Jeremy Friesner Dec 30 '21 at 18:48

1 Answers1

4

Sockets are not the only type of file descriptor which you can make non-blocking. In theory, you can mark any file descriptor as non-blocking (by specifying O_NONBLOCK when you open() the file) but it's possible that the setting will be ignored (for regular files or special files which don't implement nonblocking mode). So the non-blocking flag is part of the general file interface.

By contrast, the socket timeouts apply only to sockets. That's made clear by the fact that you can only set them using a socket-specific interface. (Terminal devices have two read timeout attributes -- VTIME and VMIN -- which are vaguely related, but with very different semantics. Those are set with the termios interface.)

There are very few generally-applicable attributes which can be manipulated with fcntl. There are lots of attributes which are specific to certain types of files, and which are manipulated using a variety of specific interfaces.

rici
  • 234,347
  • 28
  • 237
  • 341