C language to wait for socket connection and socket location method

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

C listen() function: wait for a connection
The header file:


#include <sys/socket.h>

Definition function:


int listen(int s, int backlog);

Function description: The parameter backlog specifies the maximum number of connections that can be processed at the same time. If the number of connections reaches this limit, the client will receive an error from the econnhence. Then we call accept().

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

Note: listen() only applies to the socket type of SOCK_STREAM or SOCK_SEQPACKET. If the socket is AF_INET, the maximum parameter backlog can be set to 128.

Error code:
    EBADF parameter sockfd invalid socket handling code
    Insufficient EACCESS
    The socket specified by EOPNOTSUPP does not support the listen mode.

C language bind() function: socket location
The header file:


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

Function: int bind(int sockfd, struct sockaddr * my_addr, int addrlen);

Bind () is used to set a name for the socket with parameter sockfd. This name points to a sockaddr structure with parameter my_addr, and defines a common data structure for different socket domains


struct sockaddr
{
  unsigned short int sa_family;
  char sa_data[14];
};

1. Sa_family is the domain parameter when calling socket(), that is, the value of AF_xxxx.
2. The maximum length of sa_data is 14 characters.

This sockaddr structure is defined differently depending on the socket domain, for example, using the AF_INET domain, its socketaddr structure is defined as


struct socketaddr_in
{
  unsigned short int sin_family;
  uint16_t sin_port;
  struct in_addr sin_addr;
  unsigned char sin_zero[8];
};

struct in_addr
{
  uint32_t s_addr;
};

1. Sin_family is sa_family
2. Sin_port is the port number used
3. Sin_addr.s_addr is not used for the IP address sin_zero.
The parameter addrlen is the structure length of sockaddr.

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

Error code:
1. The EBADF parameter sockfd is illegal socket processing code.
2. Insufficient EACCESS
3. The ENOTSOCK parameter sockfd is a file descriptor, not a socket.


Related articles: