Tutorial by Examples

In this example, we'll create a simple echo server that will listen on the specified port, and being able to handle new connections: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h&...
This is a client-server example. The process forks and runs client in the parent process and server in the child process: client connects to server and waits until server exits; server accepts connection from client, enables keepalive, and waits any signal. Keepalive is configured using the f...
This is a TCP daytime iterative server kept as simple as possible. #include <sys/types.h> /* predefined types */ #include <unistd.h> /* unix standard library */ #include <arpa/inet.h> /* IP addresses conversion utilities */ #include <netinet/in.h> /* sockaddr...
This is a TCP daytime client kept as simple as possible. #include <unistd.h> /* unix standard library */ #include <arpa/inet.h> /* IP addresses manipulation utilities */ #include <netinet/in.h> /* sockaddr_in structure definition */ #include <sys/socket.h> /* ber...
There are four types of sockets available in POSIX API: TCP, UDP, UNIX, and (optionally) RAW. Unix domain sockets may act like stream sockets or like datagram sockets. Some of endpoint types: struct sockaddr - universal endpoint type. Typically, other concrete endpoint types are converted to thi...
A C program that wishes to accept network connections (act as a "server") should first create a socket bound to the address "INADDR_ANY" and call listen on it. Then, it can call accept on the server socket to block until a client connects. //Create the server socket int servsoc...
POSIX.1-2008 Given the name of a server as a string, char* servername, and a port number, int port, the following code creates and opens a socket connected to that server. The "name" of the server can either be a DNS name, such as "www.stackoverflow.com," or an IP address in sta...
Even when sockets are in "blocking" mode, the read and write operations on them do not necessarily read and write all the data available to be read or written. In order to write an entire buffer into a socket, or read a known quantity of data from a socket, they must be called in a loop. ...

Page 1 of 1