Monday, September 5, 2011

getsockopt : Getting Socket Options


Oftentimes, an application needs to determine what the current option settings are for a socket. This is especially true of a subroutine library function, which will have no prior knowledge of what was done with the socket, which was passed to it as an argument. The application might also need to know things such as the optimal buffer size to use, which is determined by the system defaults.

The function that permits you to inspect socket option values is the getsockopt(2) function. Its function synopsis is given as follows:

#include <sys/types.h>
#include <sys/socket.h>

int getsockopt(int s,
               int level,
               int optname,
               void *optval,
               socklen_t *optlen);

The five arguments are described as follows:
  1. The socket s from which to inspect the option.
  2. The protocol level at which the option is to be inspected.
  3. The option optname to inspect.
  4. The pointer optval pointing to the receiving buffer for the option value.
  5. The pointer optlen pointing to both the input buffer length, and the returned option length values.

The return value from this function returns zero when successful. When an error occurs, -1 is returned and the external variable errno contains the nature of the error.

The protocol level argument indicates where in the protocol stack you want to access an option. Usually, you will use one of these:
  • SOL_SOCKET to access socket level options
  • SOL_TCP to access TCP level options

The discussion in this chapter will center strictly on the use of SOL_SOCKET level options. The optname argument is an integer value. The value used here will be determined first by the choice of the level argument value used. Within a specified protocol level, the optname argument will determine which option you want to access. Table 12.1 shows some of the level and option combinations that are possible.

Table 12.1: Protocol Level and Option Names
Protocol Level
Option Name
SOL_SOCKET
SO_REUSEADDR
SOL_SOCKET
SO_KEEPALIVE
SOL_SOCKET
SO_LINGER
SOL_SOCKET
SO_BROADCAST
SOL_SOCKET
SO_OOBINLINE
SOL_SOCKET
SO_SNDBUF
SOL_SOCKET
SO_RCVBUF
SOL_SOCKET
SO_TYPE
SOL_SOCKET
SO_ERROR
SOL_TCP
SO_NODELAY

Most of the options listed in the table are socket level options, where the level was given as SOL_SOCKET. One TCP level socket option was included for comparison purposes, where its level is specified as SOL_TCP.

Many socket options are retrieved into an int data type. When looking at the manual pages, data type int can usually be assumed unless otherwise indicated. When a Boolean value is used, the
int value indicates TRUE when the value is nonzero and indicates FALSE when it is zero.


Example:
Using getsockopt example C code

No comments:

Post a Comment