C language to set and get the socket state of the relevant function usage

  • 2020-04-02 03:21:11
  • OfStack

C language setsockopt() function: set socket state
The header file:


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

Definition function:


int setsockopt(int s, int level, int optname, const void * optval, ,socklen_toptlen);

Setsockopt () is used to set the socket state specified by parameter s. parameter level represents the network layer to be set, generally set as SOL_SOCKET to access the socket layer.
    SO_DEBUG turns debug mode on or off
    SO_REUSEADDR allows local addresses to be reused during the bind () procedure
    SO_TYPE returns socket form.
    SO_ERROR returns the reason for the socket error that occurred
    Packets sent out by SO_DONTROUTE should not be transmitted using routing equipment.
    SO_BROADCAST is delivered in a broadcast mode
    SO_SNDBUF sets the size of the sent staging area
    SO_RCVBUF sets the size of the received staging area
    SO_KEEPALIVE periodically determines whether the connection has terminated.
    SO_OOBINLINE sends OOB data to the standard input device as soon as it is received
    SO_LINGER ensures that data is transmitted safely and reliably.

The parameter optval represents the value to be set, and the parameter optlen is the length of optval.

Return value: 0 on success, -1 on error, error reason in errno.

Additional notes:
1. EBADF parameter s is not valid socket processing code
2. ENOTSOCK parameter s is a file descriptor, not a socket
3. The option specified by the ENOPROTOOPT parameter optname is incorrect.
4. EFAULT parameter optval points to an inaccessible memory space.

C language getsockopt() function: get socket state
The header file:


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

Definition function:


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

Getsockopt () returns the socket state specified by parameter s. optname represents the state of the options to be obtained, optval refers to the memory address to be saved, and optlen refers to the size of the space.

Return value: 0 on success, -1 on error, error reason in errno

Error code:
1. EBADF parameter s is not valid socket processing code
2. ENOTSOCK parameter s is a file descriptor, not a socket
3. The option specified by the ENOPROTOOPT parameter optname is incorrect
4. EFAULT parameter optval points to an inaccessible memory space

sample


#include <sys/types.h>
#include <sys/socket.h>
main()
{
  int s;
  int optval;
  int optlen = sizeof(int);
  if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  perror("socket");
  getsockopt(s, SOL_SOCKET, SO_TYPE, &optval, &optlen);
  printf("optval = %dn", optval);
  close(s);
}

Perform:


optval = 1 //This is the definition of SOCK_STREAM


Related articles: