accept4 - Linux


Overview

The accept4() system call accepts an incoming connection on a socket and creates a new socket for communication, returning four values: the accepted socket descriptor, the peer address, the peer address length, and additional socket flags. It is typically used for server applications that need to handle multiple simultaneous client connections.

Syntax

#include <sys/socket.h>

int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags);

Options/Flags

The flags argument can include the following options:

  • SOCK_NONBLOCK: Sets the accepted socket to non-blocking mode.
  • SOCK_CLOEXEC: Closes the accepted socket when the process exits.

Examples

Simple Server

#include <sys/socket.h>
#include <netinet/in.h>

int main() {
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(8080);
  addr.sin_addr.s_addr = INADDR_ANY;

  bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
  listen(sockfd, 5);

  while (1) {
    int new_sockfd, addrlen = sizeof(addr);
    new_sockfd = accept4(sockfd, (struct sockaddr*)&addr, &addrlen, SOCK_NONBLOCK);
    // Handle the new connection in a separate thread or process
  }

  return 0;
}

Client

#include <sys/socket.h>
#include <netinet/in.h>

int main() {
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(8080);
  addr.sin_addr.s_addr = inet_addr("127.0.0.1");

  connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
  // Send and receive data using the socket
  
  close(sockfd);
  return 0;
}

Common Issues

  • Invalid socket descriptor: Ensure that the sockfd argument is a valid open socket.
  • Buffer overflow: The addrlen argument must be large enough to hold the incoming peer address.
  • Non-listening socket: The sockfd must be configured to listen for incoming connections before calling accept4().

Integration

accept4() can be used with other Linux commands and tools for advanced tasks:

  • Combine with select() or poll() for efficient multiplexing of multiple sockets.
  • Use with fork() or threads for handling multiple client connections simultaneously.

Related Commands

  • socket(): Creates a new socket.
  • bind(): Binds a socket to a specific address and port.
  • listen(): Configures a socket to listen for incoming connections.
  • connect(): Initiates a connection to a remote host.
  • epoll_wait(): Monitors multiple file descriptors for events, including incoming connections.