lOMoARcPSD|63503577
Network Module-3
Network Programming (Visvesvaraya Technological University)
Scan to open on Studocu
Studocu is not sponsored or endorsed by any college or university
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
MODULE-3
I/O Mul plexing
Defini on:
I/O mul plexing is a technique that allows a process to monitor mul ple I/O descriptors (like sockets, files, terminals) at
the same me and be no fied when one or more of them become ready for I/O.
Why needed?
o If a server handles mul ple clients, instead of crea ng a process/thread for each, the server can use select() /
poll() / epoll() to wait for events on mul ple sockets simultaneously.
o Efficient for network servers, chat applica ons, etc.
Key Idea:
Process tells the kernel: “Here’s a list of descriptors I’m interested in.”
Kernel returns: “These descriptors are ready.”
Different I/O Models
1. Blocking I/O Model
Default model.
A system call (e.g., recvfrom()) waits un l
data is available.
Steps:
1. Applica on calls recvfrom().
2. Kernel waits un l data arrives.
3. Kernel copies data to user buffer.
4. Call returns.
Disadvantage: Process is blocked the
whole me.
Example: A simple TCP client reading from a
socket.
2. Non-Blocking I/O Model
Socket is set to non-blocking.
When app calls recvfrom(), if no data is available
→ it returns immediately with an error
(EWOULDBLOCK).
Applica on keeps trying (polling).
Disadvantage: Wastes CPU cycles if data is not
ready.
Example: Repeatedly calling recvfrom() in a loop un l
data arrives.
3. I/O Mul plexing Model (select / poll)
Uses func ons like select(), poll(), epoll()
(Linux).
Applica on gives kernel a list of sockets.
Kernel blocks un l one or more are ready.
Then applica on calls recvfrom() on the ready
ones.
Advantage: Efficiently handles many
connec ons in a single process.
Example: A web server handling many clients using
select().
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
4. Signal-Driven I/O Model
Applica on enables I/O signals (SIGIO).
When descriptor is ready, kernel sends a
signal to the process.
Process handles it using a signal handler,
then calls recvfrom() to read the data.
Rarely used, because signals add
complexity.
5. Asynchronous I/O Model
Applica on issues an aio_read() call (POSIX
AIO).
Kernel performs opera on in background.
When finished, kernel no fies the
applica on (via signal or comple on).
Most efficient because applica on can do
other work while I/O happens.
Example: High-performance servers and
databases.
Summary of I/O Models
Model Wai ng for data Copying data Process blocked? Example Use
Blocking I/O Yes Yes Yes Simple client
Non-Blocking I/O No (returns immediately) Yes No, but busy loop Low-level polling
I/O Mul plexing Yes (via select/poll) Yes Yes, but on mul ple descriptors Mul -client servers
Signal-Driven I/O No (kernel sends signal) Yes No Event-driven apps
Asynchronous I/O No No No High-perf servers
In prac ce:
Blocking I/O is simplest.
I/O mul plexing is most
common in servers.
Asynchronous I/O is best
for high performance but
harder to implement.
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
1. SELECT FUNCTION AND STR_CLI FUNCTION.
.,select() Func on
Defini on
select() is a system call used for I/O mul plexing.
It allows a program to monitor mul ple file descriptors (sockets, files, pipes, terminals, etc.) simultaneously and wait un l one or
more of them are ready for reading, wri ng, or have an excep on.
Func on Prototype
#include <sys/select.h>
#include <sys/ me.h>
int select(int maxfdp1, fd_set *readfds, fd_set *writefds,
fd_set *excep ds, struct meval * meout);
Arguments
1. maxfdp1
o Highest-numbered file descriptor in any set + 1.
o Kernel checks all descriptors from 0 → maxfdp1-1.
2. readfds
o Set of descriptors to check if ready for reading.
o Example: socket has data to read.
3. writefds
o Set of descriptors to check if ready for wri ng.
o Example: socket buffer has space.
4. excep ds
o Set of descriptors to check for excep ons.
o Example: out-of-band (OOB) data on TCP.
5. meout
o How long to wait.
o NULL → wait indefinitely.
o 0 → poll, return immediately.
o Specific meval → wait that long.
Return Value
> 0 : Number of descriptors ready.
= 0 : Timeout expired, no descriptor ready.
< 0 : Error.
Suppor ng Macros
FD_ZERO(fd_set *set); // Clear all fds
FD_SET(int fd, fd_set *set); // Add fd
FD_CLR(int fd, fd_set *set); // Remove fd
FD_ISSET(int fd, fd_set *set); // Test if fd is ready
Use Case
Mul plex mul ple client connec ons.
Instead of blocking on one socket, we monitor many sockets at once.
2. str_cli() Func on
Defini on
str_cli() is a client func on used in TCP examples (from Stevens’ Unix Network Programming).
Purpose: Handle interac on between client and server.
It reads input from standard input (keyboard) and sends it to the server, while also reading the server’s reply and displaying
it.
Problem in Simple Version
If we use blocking I/O, the client might block on:
fgets(stdin) wai ng for user input, OR
read(sockfd) wai ng for server response.
This means client cannot handle both keyboard input and server data simultaneously.
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
Improved Version (with select())
We use select() to monitor two descriptors:
1. fileno(stdin) → for user input.
2. sockfd → for server reply.
This way:
If user types something → read from stdin, send to server.
If server sends something → read from socket, print to stdout.
Pseudo Code of str_cli()
void str_cli(FILE *fp, int sockfd) {
int maxfdp1;
fd_set rset;
char sendline[MAXLINE], recvline[MAXLINE];
FD_ZERO(&rset);
for (;;) {
FD_SET(fileno(fp), &rset); // monitor stdin
FD_SET(sockfd, &rset); // monitor socket
maxfdp1 = max(fileno(fp), sockfd) + 1;
select(maxfdp1, &rset, NULL, NULL, NULL);
if (FD_ISSET(sockfd, &rset)) {
if (read(sockfd, recvline, MAXLINE) == 0)
return; // server terminated
fputs(recvline, stdout);
}
if (FD_ISSET(fileno(fp), &rset)) {
if (fgets(sendline, MAXLINE, fp) == NULL)
return; // EOF on stdin
write(sockfd, sendline, strlen(sendline));
}
}
}
Key Points
select() helps the client handle mul ple inputs (keyboard + socket).
Without select(), the client could get stuck wai ng on one input while ignoring the other.
str_cli() is a prac cal demonstra on of using select() for mul plexing.
In exams:
Write defini on + prototype of select().
Explain parameters & macros.
Then explain problem of blocking I/O in str_cli().
Show improved version with select().
Draw a diagram of client ↔ server + stdin handling.
Batch Input and Buffering – Simplified Explana on
1. Problem with Stop-and-Wait Mode
In the basic client program (str_cli), the client sends one line at a me to the server, waits for the reply, and then sends the next line.
This is fine for interac ve use (like cha ng), but very slow for large input files.
Why? Because every line requires at least one round-trip me (RTT) between client and server. If we send thousands of lines, the
total me becomes very large.
2. Understanding the Stop-and-Wait Timeline
In stop-and-wait, the sequence looks like this:
Client sends one request → waits → gets one reply → repeats.
Even if the network is fast, the wai ng me between requests wastes bandwidth.
For example, if RTT is 175 ms and we send 2000 lines, the total me can reach 350 seconds (~6 minutes). That’s very inefficient.
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
3. Batch Mode – The Solu on
In batch mode, instead of wai ng for replies, the client keeps sending requests
con nuously.
The server processes requests as they arrive.
Replies also come back con nuously.
This way, the communica on channel is always full, and the input and
output “pipes” are u lized properly.
So, in batch mode:
Request1, Request2, Request3 … are sent without wai ng.
Replies 1, 2, 3 … come back as soon as they’re ready.
This greatly reduces the total me required.
4. The Half-Close Problem
There’s a catch: How does the server know when the client has finished sending
input?
If the client closes the socket, it can’t read the replies.
If the client keeps it open, the server doesn’t know if more data is
coming.
The solu on is to use half-close:
Client calls shutdown(sockfd, SHUT_WR) a er sending all input.
This sends a FIN signal to the server, meaning “no more input,” but the
socket remains open for reading replies.
5. Buffering Issues
When using stdio func ons like fgets and select, there’s another problem.
select() only tells us if data is in the stdio buffer, not whether it has been
fully consumed.
Some mes unread data remains in the buffer, leading to errors or missed inputs.
This makes mixing stdio buffering with select() very tricky.
The be er approach is to use unbuffered I/O (read, write) directly with sockets, so we have complete control.
Summary (Easy Recall)
Stop-and-Wait Mode: One request → one reply → very slow.
Batch Mode: Send all requests at once, replies come as fast as possible. Much faster.
Half-Close: Tells server input is finished, but s ll allows reading replies.
Buffering Problem: stdio (fgets, select) can leave unread data in buffer → error-prone. Prefer read/write.
shutdown() Func on in Sockets
1. What it Does
The shutdown() func on is used to par ally close a TCP connec on.
With close(), the socket is completely closed (both reading and wri ng).
With shutdown(), we can close only one direc on of communica on — either sending or receiving — while keeping the
other direc on open.
This is called a half-close in TCP.
2. Func on Prototype
int shutdown(int sockfd, int how);
sockfd → The socket file descriptor.
how → Specifies which part of the connec on to close.
Values for how:
SHUT_RD (0) → Close the reading side. Cannot read more
data.
SHUT_WR (1) → Close the wri ng side. Cannot send more
data (sends a FIN).
SHUT_RDWR (2) → Close both reading and wri ng sides
(like close()).
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
3. Why Use shutdown()?
Suppose the client has finished sending all requests but s ll needs to receive replies.
If it calls close(), the socket is gone → can’t read replies.
If it does nothing, the server won’t know that input is finished.
Solu on → call
shutdown(sockfd, SHUT_WR);
This tells the server:
“I won’t send any more data.”
But the socket stays open for reading replies.
4. Example Usage
// Client finished sending all data
shutdown(sockfd, SHUT_WR);
// S ll able to receive replies
while (read(sockfd, buffer, sizeof(buffer)) > 0) {
prin ("Server: %s\n", buffer);
}
5. Key Points to Remember
shutdown() is for TCP sockets, not files or UDP.
SHUT_WR is most commonly used → tells server input is done but s ll read output.
Useful in batch mode communica on (send all input first, then only read replies).
close() closes the socket completely, while shutdown() gives more control.
Summary in one line:
The shutdown() func on lets you close just one direc on of a TCP socket (send or receive), which is very useful when the client
finishes sending data but s ll needs to read replies.
TCP echo server-client concept and provided a simple C implementa on.
TCP Echo Server–Client Program Explana on
What is TCP?
TCP (Transmission Control Protocol) is a connec on-oriented protocol.
Ensures reliable data transfer: no loss, no duplica on, correct order.
Used in applica ons like web browsing, email, and file transfer.
What is an Echo Server?
A server that receives a message from a client and then sends the same message back to the client.
Useful for tes ng and understanding client-server communica on.
Program Flow
Server (server.c)
1. Create socket → using socket().
2. Bind socket → bind to IP & Port (bind()).
3. Listen → server waits for clients (listen()).
4. Accept connec on → block un l a client connects (accept()).
5. Read data → receive message from client (read()).
6. Send response → reply back to client (send()).
7. Close sockets → free resources (close()).
Client (client.c)
1. Create socket → using socket().
2. Set server address → IP & Port of server.
3. Connect → establish connec on with server (connect()).
4. Send message → client sends text to server (send()).
5. Read response → client reads server’s reply (read()).
6. Close socket → end connec on.
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
PROGRAM-4
Server.c Client.c
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#define PORT 8080 #define PORT 8080
int main() { int main() {
int s = socket(AF_INET, SOCK_STREAM, 0); int s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(PORT), struct sockaddr_in addr = {AF_INET, htons(PORT)};
INADDR_ANY}; inet_pton(AF_INET, "[Link]", &addr.sin_addr);
bind(s, (struct sockaddr*)&addr, sizeof(addr)); connect(s, (struct sockaddr*)&addr, sizeof(addr));
listen(s, 1);
send(s, "Hello from client", 17, 0);
prin ("Listening on :%d\n", PORT); char buf[1024];
int c = accept(s, NULL, NULL); read(s, buf, sizeof(buf)-1);
prin ("Server: %s\n", buf);
char buf[1024]; close(s);
read(c, buf, sizeof(buf)-1); }
prin ("Client: %s\n", buf);
send(c, "Hello from server", 17, 0);
close(c); close(s);
}
EXECUTION
1. Save the file with the name server.c 1. Save the file with the name client.c
2. Compile: gcc server.c -o server 2. Compile: gcc client.c -o client
3. Run: ./server 3. Run: ./client
4. Expected Output: 4. Expcted Output:
Listening on :8080 Server: Hello from server
Client: Hello from client
socket() → creates endpoint.
bind() → assigns IP + Port.
listen() → server ready for connec ons.
accept() → waits for client.
connect() → client requests connec on.
read() / send() → data transfer.
close() → closes connec on.
This is a single-threaded TCP Echo Server-Client → handles one client at a me.
If mul ple clients are needed, mul threading or forking must be added.
pselect in plain words, without code:
What is pselect?
pselect is almost the same as the older select func on.
Both are used in I/O mul plexing – wai ng for mul ple input/output events (like reading from several sockets or files) at the same
me.
But pselect improves on select in two important ways:
1. More precise meout
select uses a structure that measures me only up to microseconds.
pselect uses a newer structure that can measure me up to nanoseconds.
This means pselect can wait more accurately.
2. Safer handling of signals
Some mes while wai ng for input/output, a signal (like pressing Ctrl+C) can arrive.
With select, there is a race condi on:
o The signal might come just before the program calls select.
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])
lOMoARcPSD|63503577
o If that happens, the program could miss the signal and get stuck wai ng forever.
pselect solves this by le ng you provide a signal mask:
o Before wai ng, it can temporarily block certain signals.
o While wai ng, the system ensures signals and input/output are handled in a coordinated way.
o When the wait is over, the signal mask is restored.
This guarantees that signals will not be missed.
In simple terms
select = waits for mul ple I/O events, but can some mes miss signals.
pselect = does the same, but with nanosecond precision and safe signal handling, so no signals are lost.
poll func on in simple words, without code.
What is poll?
poll is another system call, like select and pselect, that allows a program to wait for mul ple input/output (I/O) events at the same
me.
For example:
A server may be connected to hundreds of clients.
Instead of checking each connec on one by one, the server can use poll to wait un l any one of them is ready (to read or
write).
How does poll work?
You give poll a list of file descriptors (like sockets, pipes, or files).
For each file descriptor, you also say what event you are interested in:
o Ready to read?
o Ready to write?
o Error on the connec on?
Then, poll waits un l one or more of them are ready, or un l a meout occurs.
When poll finishes:
It tells you which file descriptors are ready, so your program can handle them.
Differences between poll and select
1. No fixed size limit
o select has a built-in maximum number of file descriptors (o en 1024).
o poll does not have this limit; it scales be er with many connec ons.
2. Easier to manage
o With select, you work with special sets of bits (bitmasks), which can be tricky.
o With poll, you just work with an array/list of file descriptors and their events – simpler to handle.
3. Performance
o For a very large number of connec ons, poll is usually more efficient and flexible than select.
In simple terms
Think of poll like a security guard watching mul ple doors in a building:
Each door = a file descriptor.
You tell the guard: “Let me know if someone tries to enter through this door, or if there’s any trouble.”
The guard (poll) waits and then comes back to you with a list of which doors had ac vity.
Downloaded by Mahadevaswamy S N (snmahadevaswamy@[Link])