socket()

PROTOTYPE

#include <sockets.h>

int socket(int family, int type, int protocol);

DESCRIPTION

socket() allocates a socket control block. A socket is an end point for network communication. All calls to either send or receive data require a socket identifier as a parameter. Socket identifiers are also used for configuration (i.e. listen() and setsockopt()).

family is AF_INET to allocate an IPv4 socket or AF_INET6 to allocate an IPv6 socket. type is SOCK_STREAM to specify a TCP socket or SOCK_DGRAM to specify a UDP socket. protocol may be 0. Otherwise, it must be TCP for stream sockets or UDP for datagram sockets.

If successful, socket() returns a valid socket identifier. Otherwise, it sets errno and returns -1.

ERROR CODES

EMFILE Unable to allocate a socket descriptor, all sockets in use.
ENETDOWN TargetTCP has not been initialized.
EPFNOSUPPORT family is neither AF_INET nor AF_INET6.
EPROTOTYPE protocol is neither zero, TCP (for SOCK_STREAM), nor UDP (for SOCK_DGRAM).
ESOCKTNOSUPPORT type is neither SOCK_STREAM nor SOCK_DGRAM.

EXAMPLE

  /*-------------------------------------------------------------------*/
  /* Allocate a TCP socket.                                            */
  /*-------------------------------------------------------------------*/
  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock == -1)
  {
    perror("socket() failed");
    return -1;
  }