Socket Programming
In questa pagina 9
Client-server model
Network services follow the client/server model: servers receive requests and provide responses, clients are the user programs. A server normally answers more than one client, so many programs can interact at the same time; the interaction is always many to one and the server has a privileged role. Web pages, e-mail, ftp, telnet and practically every Internet service follow this model.
Servers are of two kinds:
- Iterative: answers a request and stays busy until the response is complete; only then it can serve another request.
- Concurrent: for each request it creates a child process (or a thread) that provides the service, and the server immediately waits for further requests; the child usually ends when done, the original server stays active. Several requests are served simultaneously on multitasking systems.
Networks, protocols, TCP/IP
- A computer network: hosts (run applications), routers (forward information), communication channels.
- Packets are sequences of bytes with control information (e.g. the destination host).
- A protocol is an agreement on the meaning, structure and size of packets (e.g. HTTP).
- Protocol suites/families, e.g. TCP/IP: end-to-end connectivity that specifies how data is formatted, addressed, transmitted, routed and received. Usable on the Internet and on private networks, organized in layers: application (FTP, SMTP, ...), transport (TCP or UDP), network (IP), communication channels.
- IPv4 address: 32 bits split into 4 octets (8-bit fields, 0-255 in decimal notation).
TCP vs UDP
Both use port numbers: application-specific endpoints, 16-bit unsigned integers (0 to 65535), providing end-to-end transport.
| UDP (User Datagram Protocol) | TCP (Transmission Control Protocol) | |
|---|---|---|
| Connection | connectionless: the app gives the destination of each packet | connection-oriented, bidirectional |
| Reliability | no acknowledgements, no retransmissions, out of order and duplicates possible | reliable byte stream: in order, all arrive, no duplicates; flow control |
| Style | datagrams | like file I/O |
| Used for | quick lookups, single-use query-reply | services with large data volume and persistent connection |
Default ports from the slides:
| Service | Protocol | Port |
|---|---|---|
| DNS lookup (Domain Name System) | UDP | 53 |
| FTP | TCP | 21 |
| HTTP | TCP | 80 |
| SNMP (Simple Network Management Protocol) | UDP | 161 |
| Telnet | TCP | 23 |
| DHCP (Dynamic Host Configuration Protocol) | UDP | 67/68 |
Sockets
A socket is a communication end between processes: the abstraction (Berkeley sockets, the standard API for networking) through which an application sends and receives data, giving generic access to interprocess communication. Socket programming connects two nodes: the signals are sent and received through the sockets on each node. Sockets extend the UNIX I/O: a socket is a file descriptor, and read/write work on it.
A socket is uniquely identified by a network address, an end-to-end protocol (TCP or UDP) and a port number. Internal data: family (AF_INET), service (SOCK_STREAM), local/remote IP, local/remote port.
- Stream sockets (TCP): reliable byte-stream service.
- Datagram sockets (UDP): best-effort datagram service, messages up to 65,500 bytes.
A socket lets applications talk either over the Internet or within the same computer.
Overview of the calls
| Server | Client |
|---|---|
socket |
socket |
setsockopt |
|
bind |
|
listen |
|
accept (blocks until a client connects) |
connect |
read/write (or send/recv) |
read/write |
close |
close |
The client sends the connection request; the connection is established over the transport layer; then both sides exchange information with read and write; finally the nodes close the connection. Headers: sys/socket.h (and netdb.h for the name functions).
Server side
socket()
int socket(int domain, int type, int protocol);
int server_fd = socket(AF_INET, SOCK_STREAM, 0);- domain (address family):
AF_LOCAL/AF_UNIX= local communication on the same node (UNIX domain sockets);AF_INET= IPv4,AF_INET6= IPv6 (internet domain sockets);AF_BLUETOOTH= low-level Bluetooth. - type:
SOCK_STREAM= TCP, reliable byte stream, connection-based (stream sockets);SOCK_DGRAM= UDP, unreliable, connectionless (datagram sockets). - protocol: a number;
0when the family has only one protocol, otherwise the specific number. - Returns a file descriptor used in all later calls, or
-1on error.
setsockopt()
Sets options that control the behavior of the socket.
int setsockopt(int socket_descriptor, int level, int option_name,
const void *value_of_option, socklen_t option_length);
int opt = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));level: where the option applies:SOL_SOCKET(socket level),IPPROTO_TCP(TCP level).option_nameexamples:SO_DEBUG(record debugging information),SO_REUSEADDR(allow reusing local addresses inbind()),SO_SNDBUF(maximum send buffer size),SO_LINGER(linger on close).value_of_option/option_length: the value and the size of the variable holding it.- Returns
0on success,-1on failure.
Abortive close (immediate teardown) with SO_LINGER:
struct linger {
int l_onoff; // 0 = disable linger, non-zero = enable linger
int l_linger; // time in seconds to linger
};
struct linger ling = { .l_onoff = 1, .l_linger = 0 };
if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) {
perror("setsockopt SO_LINGER abortive");
return 1;
}bind()
Assigns an address (IP and port) to the socket.
int bind(int socket_descriptor, const struct sockaddr *address, socklen_t length_of_address);
struct sockaddr_in address;
socklen_t addrlen = sizeof(address);
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
bind(server_fd, (struct sockaddr*)&address, sizeof(address));The address is filled in a struct sockaddr_in (it can hold port and address) and cast to struct sockaddr. Returns 0 on success, -1 on failure.
struct sockaddr_in and struct sockaddr
IPv4 socket address, built on the generic struct sockaddr:
struct sockaddr_in {
sa_family_t sin_family; // Address family (e.g., AF_INET)
uint16_t sin_port; // Port number (network byte order)
struct in_addr sin_addr; // IPv4 address (32-bit)
char sin_zero[8]; // Padding to match size of sockaddr
};
struct in_addr {
uint32_t s_addr; // 32-bit IPv4 address (network byte order)
};
struct sockaddr {
sa_family_t sa_family; // Address family (e.g., AF_INET for IPv4)
char sa_data[14]; // Protocol-specific address data
};| Field | Use |
|---|---|
sin_family |
for IPv4 always AF_INET |
sin_port |
port in network byte order (big-endian): address.sin_port = htons(8080); (host-to-network short) |
sin_addr |
IPv4 address: address.sin_addr.s_addr = inet_addr("127.0.0.1"); or inet_pton(AF_INET, "127.0.0.1", &address.sin_addr);; INADDR_ANY for any local address |
sin_zero |
8 bytes of padding so the struct has the size of sockaddr; typically zeroed: memset(address.sin_zero, 0, sizeof(address.sin_zero)); |
listen()
int listen(int socket_descriptor, int back_log);
listen(server_fd, 3);Turns the socket from an active socket (used for connecting) into a listening socket (used for accepting connections), on the address and port given to bind(). It is non-blocking: it returns right after setting up the queue. backlog = maximum number of pending connection requests queued before accept() is called; beyond it new attempts may be refused (error or ignored). Returns 0 or -1.
accept()
int accept(int socket_descriptor, struct sockaddr *address, socklen_t *length_of_address);
struct sockaddr_in clientAddr;
socklen_t addrSize = sizeof (clientAddr);
nw_socket = accept(server_fd, (struct sockaddr*)&clientAddr, &addrSize);Typically blocks until a client connects. It extracts the first connection request from the queue of pending connections, creates a new socket for that connection and returns its file descriptor; the new descriptor is the one used with read/write to talk to the client (the listening socket keeps listening). address receives the client's address, length_of_address its size.
read() and write()
ssize_t read(int socket_descriptor, void *buffer, size_t size);
ssize_t write(int socket_descriptor, void *buffer, size_t count);
ssize_t valread;
char buffer[1024];
valread = read(nw_socket, buffer, 1024 - 1);
// subtract 1 for the null terminator at the end
char hello[] = "Hello from server";
write(nw_socket, hello, strlen(hello));readreturns the number of bytes read (0 = end of stream); fewer bytes than requested is not an error;-1on error witherrnoset.writereturns the number of bytes written,-1on error (errnoset).- The descriptor is the one returned by
accept().
close()
int close(socket_descriptor);Deallocates the descriptor (it becomes available again for later socket() calls). Descriptor from socket() or accept(). Returns 0 or -1 (errno).
Client side
Create a socket, fill in the server address, connect, exchange data, close.
// Create client socket
cliSoc = socket (AF_INET, SOCK_STREAM, 0);
if (cliSoc < 0) {
perror ("Error in socket creation");
exit (1);
}
int connect(int socket_descriptor, const struct sockaddr *address, socklen_t length_of_address);
// Set server address parameters
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons (PORT);
serverAddr.sin_addr.s_addr = inet_addr (SERVER_IP);
// Connect to the server
if (connect (cliSoc , (struct sockaddr*) & serverAddr, sizeof (serverAddr)) < 0) {
perror("Error in connecting to server");
exit (1);
}PORT and SERVER_IP are constants of the program. connect returns 0 on success and -1 on error/failure; afterwards the client also uses read/write and close.
The slides announce a complete example in which one hello message is exchanged between server and client (AF_INET model), but only the fragments above are in the extracted text: the listing is not reproduced on the slides provided.
Concurrent server
After accept, create a child with fork(): the child serves the client, the parent goes back to waiting.
pid_t pid = fork();
if (pid == 0) {
// Child process
close (serverSocket);
// receive messages from the client, read() and send() functions invocation
}
else if (pid > 0 ) {
// Parent process
close(clientSocket);
}Each process closes the descriptor it does not need: the child closes the listening socket, the parent closes the connected socket of that client.
AF_UNIX sockets (same machine)
Sockets with the AF_UNIX family can be connection-oriented (SOCK_STREAM) or connectionless (SOCK_DGRAM); both are reliable because no external communication functions are involved between the two processes.
Server flow: socket() (UNIX family, stream transport; socketpair() can also initialize a UNIX socket) -> bind() gives the socket a unique name -> listen() -> accept() (blocks indefinitely) -> recv() data from the client -> send() back -> close() descriptors -> unlink() the path name.
Client flow: socket() -> connect() -> send() -> recv() -> close().
The name space of UNIX domain sockets consists of path names: bind() creates an entry in the file system directory, and fails if the path name already exists. So the program should always call unlink() to remove the entry when it ends. (A hello-message example is announced on the slides; the listing is not in the extracted text.)
Name resolution: getaddrinfo and getnameinfo
#include <sys/socket.h>
#include <netdb.h>
int getaddrinfo(const char *nodename, const char *servname,
const struct addrinfo *hints, struct addrinfo **res);
void freeaddrinfo(struct addrinfo *ai);getaddrinfo translates a host name and/or service name into a list of socket addresses to use with socket(). It is part of modern POSIX and preferred over gethostbyname()/getservbyname() because it is protocol-independent (IPv4 and IPv6) and thread-safe.
nodename: host name ("www.example.com") or address string ("192.168.1.1","::1");NULL= local host.servname: service name ("http","ftp") or port number as a string ("80");NULL= no service. At least one of the two must be non-null.hints(may be null): restricts the result; onlyai_flags,ai_family,ai_socktype,ai_protocolare used, every other member must be zero orNULL. A nullhintsbehaves as zeros andAF_UNSPEC.res: output, a linked list ofstruct addrinfo(linked byai_next); try the addresses in the order returned. Release it withfreeaddrinfo.
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
socklen_t ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};| Field | Meaning |
|---|---|
ai_family |
AF_INET, AF_INET6, or AF_UNSPEC = any family |
ai_socktype |
SOCK_STREAM or SOCK_DGRAM; 0 = any |
ai_protocol |
protocol; 0 = any |
ai_flags |
with AI_CANONNAME the first result's ai_canonname is the official host name |
ai_addr, ai_addrlen |
pointer to the socket address and its length in bytes |
The returned ai_family, ai_socktype, ai_protocol are directly the arguments of socket(). Returns 0 on success, otherwise a nonzero error code (EAI_ADDRFAMILY, EAI_AGAIN, EAI_BADFLAGS, EAI_FAIL, EAI_FAMILY, EAI_MEMORY, EAI_NODATA, EAI_NONAME, EAI_SERVICE, EAI_SOCKTYPE, EAI_SYSTEM); gai_strerror() turns it into a readable string.
Usage pattern:
struct addrinfo *result = NULL, *ptr = NULL, hints;
...
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
rc = getaddrinfo("myhost.mydomain.com", "8080", &hints, &result);
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
mySocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
...
}Full example: print the IP addresses of a host name.
int main(int argc, char *argv[]) {
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN]; // Buffer to hold IP address (IPv4 or IPv6)
if (argc != 2) {
fprintf(stderr, "Usage: %s hostname\n", argv[0]);
return 1;
}
// Initialize the hints structure
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // Allow IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP socket
// Call getaddrinfo to resolve hostname
if ((status = getaddrinfo(argv[1], "http", &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}
printf("IP addresses for %s:\n\n", argv[1]);
// Loop through all the results
for (p = res; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// Get the pointer to the address itself
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// Convert the IP to a string and print it
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res); // Free the linked list
return 0;
}getnameinfo is the inverse: it translates a socket address into a host name and a service name (or port number); replaces gethostbyaddr() and inet_ntoa() and works with IPv4 and IPv6.
int getnameinfo(const struct sockaddr *sa, socklen_t salen,
char *node, socklen_t nodelen, char *service,
socklen_t servicelen, unsigned int flags);sa,salen: socket address (sockaddr_inorsockaddr_in6) and its size.node/nodelen: buffer for the host name (ifNULLor length 0 the name is not returned; if the name cannot be found the numeric address is returned).service/servicelen: same for the service name/port.nodeandservicecannot both beNULL.flags(default: the fully-qualified domain name is returned):NI_NOFQDN: only the node-name part of the FQDN for local hosts;NI_NUMERICHOST: numeric address always;NI_NAMEREQD: error if the host name cannot be found;NI_NUMERICSERV: numeric service (port) always;NI_DGRAM: the service is a datagram service (default assumes stream).
- Returns
0(null-terminated strings, possibly truncated to the buffer sizes) or a nonzero code (EAI_AGAIN,EAI_BADFLAGS,EAI_FAIL,EAI_FAMILY,EAI_MEMORY,EAI_NONAME,EAI_OVERFLOW,EAI_SYSTEM) to be translated withgai_strerror().
Versione ripasso
- Client/server: many clients talk to one server. Iterative server answers one request at a time; concurrent server creates a child (
fork(), or a thread) for each request and goes back to waiting. - Protocols: a protocol fixes the meaning, structure and size of packets. TCP/IP layers: application (FTP, SMTP, HTTP), transport (TCP or UDP), network (IP), channels. IPv4 address = 32 bits = 4 octets (0-255). Port = 16-bit number (0-65535).
- TCP (
SOCK_STREAM): connection-oriented, reliable byte stream, in order, no duplicates, flow control (HTTP 80, FTP 21, Telnet 23). UDP (SOCK_DGRAM): connectionless datagrams, no acknowledgements or retransmissions (DNS 53, SNMP 161, DHCP 67/68). - A socket is an endpoint of communication and a file descriptor:
readandwritework on it. It is identified by address, protocol and port. - Server flow, TCP:
socket(AF_INET, SOCK_STREAM, 0)->setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))->bind->listen(fd, backlog)->accept->read/write->close. - Client flow:
socket-> fill thesockaddr_in->connect->read/write->close. The connection is established in the transport layer before any data goes through.
cliSoc = socket(AF_INET, SOCK_STREAM, 0);
if (cliSoc < 0) { perror("Error in socket creation"); exit(1); }
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
if (connect(cliSoc, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { perror("Error in connecting to server"); exit(1); }- A socket is identified by its network address, its protocol (TCP or UDP) and its port. Stream sockets (
SOCK_STREAM) give a reliable byte service; datagram sockets (SOCK_DGRAM) give best-effort messages of up to 65,500 bytes. Sockets also work between two processes on the same computer. - Iterative server: it answers one client completely before accepting the next one. Concurrent server: after
accept,fork()gives the child the client, and the parent goes back to waiting for new connections. sockaddr_infields:sin_family(alwaysAF_INETfor IPv4),sin_port(network byte order),sin_addr(32-bit address,INADDR_ANYfor any local address),sin_zero(8 bytes of padding, zeroed withmemset).- Name resolution example:
hints.ai_family = AF_UNSPEC;andhints.ai_socktype = SOCK_STREAM;beforegetaddrinfo(argv[1], "http", &hints, &res); then loop overreswithai_next, print each address withinet_ntop, and free the list.
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT); // network byte order
addr.sin_addr.s_addr = INADDR_ANY; // server; client: inet_addr(SERVER_IP)
memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
bind(server_fd, (struct sockaddr *)&addr, sizeof(addr));listenis non-blocking: it only sets the queue,backlogis the number of pending connections.acceptblocks until a client connects and returns a new descriptor for that client; the listening socket keeps listening.readreturns the bytes read, 0 = end of stream; fewer bytes than requested is normal, not an error.writereturns the bytes written.read(fd, buf, sizeof(buf) - 1)leaves room for'\0'.closefrees the descriptor.setsockoptoptions:SO_REUSEADDR(reuse a local address inbind),SO_SNDBUF,SO_LINGER({ .l_onoff = 1, .l_linger = 0 }for an abortive close),SO_DEBUG. Returns 0 or -1.- Concurrent server: after
accept,fork(). The child closes the listening socket and serves the client; the parent closes the client socket and keeps waiting. AF_UNIXsockets work on one machine: addresses are path names,bindcreates a file-system entry and fails if it already exists. Flow:socket,bind,listen,accept,recv,send,close, thenunlinkthe path.- Name resolution:
getaddrinfo(node, service, &hints, &res)returns a linked list (ai_next) of addresses to try in order, andfreeaddrinfo(res)releases it. Protocol independent (IPv4 and IPv6) and thread-safe, preferred overgethostbyname. Hints:ai_family = AF_UNSPEC,ai_socktype = SOCK_STREAM. Errors are translated withgai_strerror.
rc = getaddrinfo("myhost.mydomain.com", "8080", &hints, &result);
for (ptr = result; ptr != NULL; ptr = ptr->ai_next)
mySocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);getnameinfo(sa, salen, node, nodelen, service, servicelen, flags)is the inverse: address to host and service name. Flags:NI_NUMERICHOST(numeric address),NI_NUMERICSERV(numeric port),NI_NAMEREQD(error if no name),NI_NOFQDN,NI_DGRAM.- Typical errors: forgetting
htons; not checking-1returns; confusing the listening socket with the one returned byaccept; callingbindon an existing UNIX socket path, or not callingunlinkat the end; "address already in use" (solved withSO_REUSEADDR); not callingfreeaddrinfo.