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:
- Create the socket with the
socket()
method, specifying the network protocol to use. - Bind the socket to a network address with the
bind()
method. For IPv4, a socket is bound to an IPv4 address and a port. - Mark the socket as one that will be used to accept new connections with the
listen()
method. - Accept connections with the
accept()
method. - Send and receive messages with the
send()
andrecv()
methods. - When the communication session is finished, close the socket with the
close()
method.
From the client’s perspective, the workflow is the following:
- Create the socket with the
socket()
method, specifying the network protocol to use. - Connect to the remote socket with the
connect()
method, correctly specifying the IPv4 address and port of the server. - Send and receive messages with the
send()
andrecv()
methods. - 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 {
; /* Address family */
sa_family_t sa_familychar sa_data[]; /* Socket address */
};
struct sockaddr_in {
; /* address family: AF_INET */
sa_family_t sin_family; /* port in network byte order */
in_port_t sin_portstruct in_addr sin_addr; /* internet address */
};