Skip to content

socket()

Purpose

socket() creates a communication endpoint and returns a file descriptor.

For TCP/IPv4 examples, it is typically called with AF_INET and SOCK_STREAM.

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

Prototype

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

Minimal Example

int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0) {
    perror("socket");
    return -1;
}

Common Pitfalls

  • Forgetting that sockets are file descriptors.
  • Not setting SOCK_CLOEXEC or FD_CLOEXEC when appropriate.
  • Forgetting to make sockets non-blocking in event-loop designs.