Introduction to Socket Programming
What is a Socket?
A socket is a way to communicate with other programs using a standard UNIX file descriptor.
As you know, everything in Unix is a file. So when you want to communicate with another program, you do it through a file descriptor.
Socket Descriptors
A file descriptor is an integer associated with an open file. It can be anything, such as a network connection, a pipe, a terminal, or a real file on disk.
Because a socket descriptor is a file descriptor, it can be used like one. For example, it can be passed to the read and write functions to read and write data to the socket.
The operating system uses socket descriptors to track open sockets and identify where data should be sent to or received from.
The socket() Function
Function Parameters
1. Protocol Family (Domain)
The protocol family is a set of protocols that share the same socket address format. The protocol family determines the format of the socket address and which fields in the socket address are used to specify the host and port.
Common protocol families include:
AF_INETIPv4 protocol familyAF_INET6IPv6 protocol familyAF_UNIXUnix domain protocol familyAF_UNSPECUnspecified protocol family
Note:
AF_stands for Address Family.The
AF_INETandAF_INET6domains are used for communication over the Internet.The
AF_UNIXandAF_LOCALdomains are used for communication on the same machine, whereAF_LOCALis an alias forAF_UNIX.The
AF_UNSPECdomain is used to specify that the socket can be used with other domains.
2. Socket Type
The Type parameter determines the data transmission method of the socket.
Common socket types include:
| Type | Description |
|---|---|
| SOCK_STREAM | Provides an ordered, reliable, bidirectional, connection-oriented byte stream |
| SOCK_SEQPACKET | Provides a fixed-length, ordered, reliable, connection-oriented message |
| SOCK_DGRAM | Provides a fixed-length, connectionless, unreliable message |
| SOCK_RAW | Provides an IP datagram interface |
Note:
SOCK_SEQPACKETis similar toSOCK_DGRAMbut provides additional features such as error checking and flow control to ensure data is reliably delivered in the correct order.
3. Protocol
The Protocol parameter specifies the specific protocol used by the socket. It is usually 0, which selects the default protocol based on the given domain and socket type.
When multiple protocols are supported for the same domain and socket type, we can use the protocol parameter to select a specific protocol.
Note:
The default protocol for
SOCK_STREAMin theAF_INETdomain is TCP (RFC 793). Examples: telnet, ftp, ssh, web browsers, etc.The default protocol for
SOCK_DGRAMin theAF_INETdomain is UDP (RFC 768). Examples: DNS, DHCP, NTP, etc.| Protocol | Description | | --- | --- | | IPPROTOIP | IPv4 | | IPPROTOIPV6 | IPv6 | | IPPROTOICMP | Internet Control Message Protocol | | IPPROTORAW | Raw IP packets | | IPPROTOTCP | TCP - Transmission Control Protocol | | IPPROTOUDP | UDP - User Datagram Protocol |
How Does the socket Function Work?
Calling the socket function is similar to calling the open function. Both return a file descriptor that can be used for subsequent I/O operations.
When you are done using the socket, you can close it by calling the close function, which releases the file descriptor for reuse.
Although a socket is essentially a file descriptor, you cannot use it with any function that accepts a file descriptor as an argument. For example: lseek, because sockets do not have a file offset.
Below are some common file descriptor operations and whether sockets support them.
| Function | Description |
|---|---|
| dup | Duplicate the socket |
| close | Release the socket |
| read | Read data from the socket, equivalent to recv |
| write | Write data to the socket, equivalent to send |
| select | Wait for the socket to be ready for I/O operations |
| mmap | Not supported |
| lseek | Not supported |
Socket Addresses
To identify the specific process we want to communicate with, we need to know the process's address.
A process address consists of the machine's network address and a port number.
Byte Order

image
When communicating with a process on the same machine, we don't need to worry about the byte order of the data.
However, when communicating with a process on a different machine, we need to ensure that the byte order of the data is the same on both machines.
Big-Endian and Little-Endian
Big-Endian: The least significant byte of data is stored at the highest memory address, and the most significant byte is stored at the lowest address.
Big-endian ordering matches the writing order of data when represented in bytes, which aligns with human reading habits.
big-endian example:
| n | n + 1 | n + 2 | n +3 |
|-----|-------|-------|------|
| MSB | | | LSB |Little-Endian: When the low-order byte of a multi-byte value is stored at the smaller address and the high-order byte at the larger address, it is called little-endian.
Little-endian is opposite to human reading habits but is more natural for how computers read memory, as CPUs read data from lower addresses to higher addresses.
| n + 3 | n + 2 | n + 1 | n |
|-------|-------|-------|-----|
| MSB | | | LSB |Typically, network protocols specify a byte order so that data can be exchanged between different machines without confusion.
- The TCP/IP protocol suite uses big-endian.
Byte Order Conversion Functions
| Function | Description |
|---|---|
| htons | Convert host byte order to network byte order (16-bit) |
| htonl | Convert host byte order to network byte order (32-bit) |
| ntohs | Convert network byte order to host byte order (16-bit) |
| ntohl | Convert network byte order to host byte order (32-bit) |
h stands for host, n stands for network.
l stands for long, s stands for short.
Here are the prototypes for these functions:
Address Structures
An address identifies a socket endpoint within a specific protocol communication domain.
Different operating systems may have different implementations of address structures.
For example, in FreeBSD, the address structure is defined as follows:
In Linux systems, the address structure is:
sa_family is typically AFINET (IPv4) or AFINET6 (IPv6).
sa_data is a character array of 14 bytes used to store address information, such as the destination IP address and port number.
IPv4 Address Structure
The IPv4 address structure is defined in the header file netinet/in.h as follows:
IPv6 Address Structure
The IPv6 address structure is defined in the header file netinet/in.h as follows:
Although the sockaddr_in and sockaddr_in6 structures are different, they are both cast to a sockaddr structure when passed to socket system calls.
The sockaddr_storage Structure
The sockaddr_storage structure is designed to be large enough to hold any address structure. Since you may not know which address structure you will be dealing with, you can use this structure to hold any address structure and then cast it to the appropriate type when needed.
The sockaddr_storage structure is defined in the header file sys/socket.h as follows:
IP Address Format Conversion
Common IP address formats like 192.168.0.1 are in dotted-decimal notation, but they are stored in binary format in computers.
To print a human-readable address format, we use the inet_ntop function to convert the binary address in the computer to dotted-decimal notation, where ntop stands for "network to presentation".
To convert a human-readable address format to binary format, we use the inet_pton function, where pton stands for "presentation to network".
Both functions are thread-safe.
Function Prototypes
The inet_ntop and inet_pton functions are defined in the header file arpa/inet.h as follows:
Return Values
- inet_ntop: returns a pointer to str on success, NULL on error
- inet_pton: returns 1 on success, 0 if the input is not a valid address string, -1 on error
Parameter Description
- domain: address family, e.g., AFINET, AFINET6
- addr: pointer to the binary address
- str: pointer to the buffer that will store the human-readable address
- size: size of the str buffer
Typically, we use the
INET_ADDRSTRLENorINET6_ADDRSTRLENmacros to specify the buffer size. Their values are:- INET_ADDRSTRLEN : for IPv4 addresses, its value is 16 bytes
- INET6_ADDRSTRLEN : for IPv6 addresses, its value is 46 bytes
Example Code
Note:
The code above is not robust because it doesn't check if the IP address is valid.
The inet_pton function returns -1 on error, 0 if the input is not a valid address for the specified address family, and 1 on success.
Therefore, check if the return value is greater than 0 to ensure the conversion was successful.
Getting Hostnames and IP Addresses
getaddrinfo()
In older Unix systems, there were two functions to convert hostnames to IP addresses or IP addresses to hostnames: gethostbyname and gethostbyaddr.
However, nowadays, the getaddrinfo and getnameinfo functions are used instead because they are more robust and portable.
Below is the prototype for the getaddrinfo function:
getaddrinfo() takes three input parameters and stores the result in res. It returns an integer: 0 on success, non-zero on error.
The first parameter, node, is the hostname or IP address. If it is NULL, the IP address is set to INADDRANY for IPv4 or IN6ADDRANY_INIT for IPv6.
The second parameter, service, is the service name or port number. If it is NULL, the port number is set to 0. It can be a decimal number or a service name, such as "http" or "ftp". See more: IANA List of Well-Known Ports
The third parameter, hints, is a pointer to a struct addrinfo. It is used to specify the type of socket we want. If it is NULL, it defaults to SOCKSTREAM (TCP) and AFINET (IPv4)
The fourth parameter, res, is a pointer to a pointer to a struct addrinfo. It will point to a linked list containing information about the hostname or IP address.
Here is an example of using getaddrinfo():
Here is an example of a client that wants to connect to a server (www.example.com) on port 3490.
It doesn't connect yet, but it prepares for a future connection.
getnameinfo()
The getnameinfo() function is the inverse of getaddrinfo(): it converts a socket address into the corresponding host and service names.
Function Return Value
On success, it returns 0, and the node and service names are filled in as null-terminated strings, possibly truncated to fit the specified buffer lengths.
On error, it returns a non-zero error code, and the contents of the buffers are undefined.
Example Code
The bind() Function
Function Purpose
Once a socket is created, it must be bound to an address and port number so that other processes can connect to it.
Typically, a server calls the bind function to bind a socket to a specific port number and IP address.
Function Prototype
Function Parameters
sockfd: socket file descriptormy_addr: pointer to a struct sockaddr containing the server's port number and IP address.addrlen: the length of my_addr (struct sockaddr).
Function Return Value
Returns 0 on success, -1 on error and sets errno.
Example Code - Manually Setting IP Address and Port Number
Example Code - Using getaddrinfo()
The connect() Function
Function Purpose
Typically, a client calls the connect function to connect to a server.
Function Prototype
Function Parameters
sockfd: socket file descriptorserv_addr: pointer to a struct sockaddr containing the server's port number and IP address.addrlen: the length of serv_addr (struct sockaddr).
Function Return Value
Returns 0 on success, -1 on error and sets errno.
Example Code
Note: In the example code above, we did not call the bind() function. This is because we don't care about the local port number. We only care about the port number of the connecting party. In this case, the operating system kernel will automatically assign a port number for us, and the remote server will automatically get that port number from us.
The listen() Function
Function Purpose
The server calls the listen function to listen for connection requests from clients.
Function Prototype
Function Parameters
sockfd: socket file descriptorbacklog: the maximum length of the pending connection request queue. If the queue is full, the client will receive an error with the error code ECONNREFUSED.
Function Return Value
Returns 0 on success, -1 on error and sets errno.
Example Code
To make the server run on a specific port number, you need to call the bind function before calling the listen function.
The accept() Function
Function Purpose
Typically, the server calls the accept function to accept a connection request from a client on a specific port number.
Function Prototype
Function Parameters
sockfd: socket file descriptoraddr: pointer to a struct sockaddr that will be filled with the client's port number and IP address.addrlen: the length of addr (struct sockaddr).
Function Return Value
Returns a new socket file descriptor (non-negative integer) on success, -1 on error and sets errno.
Example Code
Note:
All send() and recv() functions are called on the new socket file descriptor returned by accept().
If you only want to accept one connection, you can call
close(sockfd)after callingaccept()to close the listening socket and prevent other connections.
The send() and recv() Functions
Function Purpose
The send and recv functions are used for communication between a client and server over stream sockets or connected datagram sockets.
For unconnected datagram sockets, use the sendto and recvfrom functions.
Function Prototype - send()
Function Parameters - send()
sockfd: socket file descriptormsg: pointer to the buffer containing the message to send.len: the length of the message to send (in bytes).flags: flags to modify the behavior of send().
Function Return Value - send()
Returns the number of bytes actually sent, which may be less than the len parameter.
On error, returns -1 and sets errno.
Example Code - send()
Function Prototype - recv()
Function Parameters - recv()
sockfd: socket file descriptorbuf: pointer to the receive buffer.len: the maximum length of the buffer (in bytes).flags: flags to modify the behavior of recv().
Function Return Value - recv()
Returns the number of bytes actually read into the buffer.
On error, returns -1 and sets errno.
If the connection has been closed, returns 0.
Example Code - recv()
The sendto() and recvfrom() Functions
Function Purpose
Because datagram sockets are not connected to a peer, we need to provide the destination address before sending a message.
The sendto and recvfrom functions are used for communication between a client and server over unconnected datagram sockets.
Function Prototype - sendto()
Function Parameters - sendto()
sockfd: socket file descriptormsg: pointer to the buffer containing the message to send.len: the length of the message to send (in bytes).flags: flags to modify the behavior of sendto().to: pointer to a struct sockaddr containing the destination address. It can be struct sockaddrin or struct sockaddrin6.tolen: an integer, can simply be set to sizeof(struct sockaddr_storage).
Function Return Value - sendto()
Returns the number of bytes actually sent, which may be less than the len parameter.
On error, returns -1 and sets errno.
Example Code - sendto()
Function Prototype - recvfrom()
Function Parameters - recvfrom()
sockfd: socket file descriptorbuf: pointer to the receive buffer.len: the maximum length of the buffer (in bytes).flags: flags to modify the behavior of recvfrom().from: pointer to a struct sockaddr that will be filled with the source address. It can be struct sockaddrin or struct sockaddrin6.fromlen: pointer to an integer that should be initialized to sizeof(struct sockaddr_storage).
Function Return Value - recvfrom()
Returns the number of bytes actually read into the buffer.
On error, returns -1 and sets errno.
Example Code - recvfrom()
Additional Information
If your program connects a datagram socket using the connect() function, you can use the send() and recv() functions instead of sendto() and recvfrom().
The socket itself is still a datagram socket, and packets still use UDP, but the socket interface will automatically add the destination and source information for you.
The close() Function
Function Purpose
The close() function closes a file descriptor so that it no longer refers to any file and can be reused.
This prevents any further reads and writes on the socket. Anyone attempting to read or write on the remote end will receive an error.
Function Prototype
Function Parameters
sockfd: socket file descriptor
The shutdown() Function
Function Purpose
The shutdown() function disables further send