Sockets Cheat Sheet

Overview

A socket is a structure that serves as an endpoint for network communication. Sockets provide a send/recv interface for communication.

The workflow to set up a socket to communicate over the Internet from the server side is the following:

  1. Create the socket with the socket() method, specifying the network protocol to use.
  2. Bind the socket to a network address with the bind() method. For IPv4, a socket is bound to an IPv4 address and a port.
  3. Mark the socket as one that will be used to accept new connections with the listen() method.
  4. Accept connections with the accept() method.
  5. Send and receive messages with the send() and recv() methods.
  6. When the communication session is finished, close the socket with the close() method.

From the client’s perspective, the workflow is the following:

  1. Create the socket with the socket() method, specifying the network protocol to use.
  2. Connect to the remote socket with the connect() method, correctly specifying the IPv4 address and port of the server.
  3. Send and receive messages with the send() and recv() methods.
  4. When the communication session is finished, close the socket with the close() method.

Below is an example of how a client-server connection happens:

Manual pages

In addition to the manual pages of the methods described above and below, you are encouraged to go check out these other manual pages too:

  • man 7 ip
  • man 3 sockaddr
  • man 3 getaddrinfo

You don’t have to read and understand them entirely (you probably shouldn’t), but they are a good source of information.

Methods

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

int socket(int domain, int type, int protocol);
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
ssize_t send(int sockfd, const void buf[.len], size_t len, int flags);
ssize_t recv(int sockfd, void buf[.len], size_t len, int flags);

Structures

struct sockaddr {
        sa_family_t     sa_family;      /* Address family */
        char            sa_data[];      /* Socket address */
};

struct sockaddr_in {
        sa_family_t    sin_family; /* address family: AF_INET */
        in_port_t      sin_port;   /* port in network byte order */
        struct in_addr sin_addr;   /* internet address */
};
Back to top