0% found this document useful (0 votes)
3 views64 pages

Network Programming

The document outlines the top 20 important questions for the VTU Network Programming course (MSCS203), covering various modules such as the OSI model, socket programming, I/O multiplexing, and advanced socket programming. It includes key concepts, definitions, and frequently asked questions that are essential for understanding network programming and client/server communication. The document serves as a study guide for students preparing for examinations in this subject.

Uploaded by

tharuni382
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views64 pages

Network Programming

The document outlines the top 20 important questions for the VTU Network Programming course (MSCS203), covering various modules such as the OSI model, socket programming, I/O multiplexing, and advanced socket programming. It includes key concepts, definitions, and frequently asked questions that are essential for understanding network programming and client/server communication. The document serves as a study guide for students preparing for examinations in this subject.

Uploaded by

tharuni382
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Top 20 Most Important VTU Questions

Network Programming (MSCS203)

� MODULE 1 – Introduction
Explain the OSI Model with neat diagram.

Explain the functions of Client/Server Communication.

Explain BSD Networking History.

Explain UNIX Standards.

� Explain 64-bit Architectures.

� Compare TCP, UDP and SCTP.

� MODULE 2 – Sockets
� Explain Socket Address Structures.

� Explain Address Conversion Functions.

� Explain Byte Ordering and Manipulation Functions.

� Explain TCP Socket Functions:

 socket()
 bind()
 listen()
 accept()
 connect()

� Explain fork() and Concurrent Server Design.

� Explain getsockname() and getpeername().


� Explain TCP Client/Server Program.

� MODULE 3 – I/O Multiplexing


Explain I/O Multiplexing.

Explain select() function.

� Explain poll() function.

� Explain shutdown() function.

� Explain TCP Echo Server.

� MODULE 4 – Advanced Socket


Programming
Explain recv() and send() functions.

Explain Socket Timeouts.

Explain readv() and writev().

� Explain sendmsg() and recvmsg().

� Explain UNIX Domain Sockets.

� Explain socketpair() function.

� Explain UNIX Domain Stream Client/Server.

� Explain UNIX Domain Datagram Client/Server.

� MODULE 5 – Client/Server Design


Explain TCP Iterative Server.

Explain TCP Concurrent Server.

Explain TCP Preforked Server.

Explain Descriptor Passing.

Explain Thread Locking around accept().

Explain File Locking around accept().

Explain One Thread Per Client Model.

� Most Repeated Questions (★★★★★)


These questions have appeared repeatedly in VTU and have a very high probability:

 ⭐ OSI Model
 ⭐ TCP vs UDP vs SCTP
 ⭐ Socket Address Structure
 ⭐ socket(), bind(), listen(), accept(), connect()
 ⭐ TCP Client–Server Program
 ⭐ select() function
 ⭐ poll() function
 ⭐ TCP Echo Server
 ⭐ UNIX Domain Sockets
 ⭐ send() and recv()
 ⭐ TCP Iterative Server
 ⭐ TCP Concurrent Server
 ⭐ Descriptor Passing

NETWORK PROGRAMMING (MSCS203)


MODULE 1 – Introduction to Network
Programming
Syllabus:
Introduction to Network Applications, Client/Server Communication, OSI Model, BSD
Networking History, Test Networks and Hosts, UNIX Standards, 64-bit Architectures, Transport
Layer – TCP, UDP and SCTP.

� Important Questions (Module 1)


Prepare these first (Most Expected VTU Questions):

1. Explain the OSI Model with neat diagram.


2. Explain Client/Server Communication.
3. Explain BSD Networking History.
4. Explain UNIX Standards.
5. Explain 64-bit Architecture.
6. Compare TCP, UDP and SCTP.
7. Explain Test Networks and Hosts.

� Introduction to Network Programming


Definition

Network Programming is the process of writing programs that communicate with other
programs over a computer network using protocols like TCP/IP, UDP, and SCTP.

It enables applications running on different computers to exchange information.

Examples:

 Web Browsers
 Email Applications
 Chat Applications
 FTP
 Video Conferencing
Network Programming Architecture
Client
|
TCP / UDP
|
Internet
|
TCP / UDP
|
Server

Applications

 Web Services
 Online Banking
 Cloud Computing
 File Sharing
 IoT Applications
 Remote Login
 Video Streaming

Advantages

 Resource sharing
 Distributed computing
 Real-time communication
 Scalability
 Centralized services

Client–Server Communication
⭐ Very Important Question

Definition

The Client–Server Model is a network architecture in which a client requests services and the
server processes the request and sends the response.
Client–Server Diagram
+---------+ Request +---------+
| Client | -------------------------------> | Server |
| | <------------------------------- | |
+---------+ Response +---------+

Components

Client

 Initiates communication
 Sends requests
 Waits for responses

Examples:

 Chrome Browser
 Mobile Apps
 FTP Client

Server

 Listens for requests


 Processes data
 Sends responses

Examples:

 Web Server
 Database Server
 Mail Server

Communication Steps

1. Client starts.
2. Server waits for connections.
3. Client sends request.
4. Server processes request.
5. Server sends response.
6. Client receives response.
Advantages

 Centralized management
 Better security
 Easy maintenance
 Resource sharing

Disadvantages

 Server failure affects clients


 High server load
 Cost of server maintenance

� OSI Model
⭐ Most Repeated VTU Question

Definition

The OSI (Open Systems Interconnection) Model is a 7-layer reference model developed by
ISO to standardize communication between network devices.

OSI Model Diagram


+--------------------------+
| 7. Application Layer |
+--------------------------+
| 6. Presentation Layer |
+--------------------------+
| 5. Session Layer |
+--------------------------+
| 4. Transport Layer |
+--------------------------+
| 3. Network Layer |
+--------------------------+
| 2. Data Link Layer |
+--------------------------+
| 1. Physical Layer |
+--------------------------+
Functions of Each Layer

1. Physical Layer

 Transmits bits
 Defines cables and connectors

Examples:

 Ethernet Cable
 Optical Fiber

2. Data Link Layer

 Frame transmission
 Error detection
 MAC addressing

Examples:

 Ethernet
 PPP

3. Network Layer

 Logical addressing
 Routing

Example:

 IP

4. Transport Layer

 Reliable communication
 Flow control
 Error control

Examples:
 TCP
 UDP
 SCTP

5. Session Layer

 Establishes sessions
 Synchronization

6. Presentation Layer

 Encryption
 Compression
 Data formatting

7. Application Layer

Provides services directly to users.

Examples:

 HTTP
 FTP
 SMTP
 DNS

Advantages

 Standard architecture
 Easy troubleshooting
 Modular design
 Interoperability

BSD Networking History


⭐ Frequently Asked

Definition

BSD (Berkeley Software Distribution) is a UNIX operating system developed at the University
of California, Berkeley.

It introduced the Socket API, which became the standard programming interface for network
communication.

Timeline

 UNIX developed at Bell Labs.


 Berkeley extended UNIX.
 BSD introduced TCP/IP support.
 Socket API became standard.
 Linux adopted BSD socket interface.

BSD Networking Diagram


Application
|
Socket API
|
TCP / UDP
|
IP
|
Network Interface

Importance

 Standard socket programming


 Reliable networking support
 Foundation of modern UNIX networking

� Test Networks and Hosts


Test Networks

Used for testing applications before deployment.

Examples:

 Loopback Network ([Link])


 Local Area Network (LAN)
 Virtual Network

Hosts

A Host is any device connected to a network with an IP address.

Examples:

 Computer
 Server
 Laptop
 Smartphone

Loopback Address
[Link]

Used to test local networking without using physical hardware.

UNIX Standards
Definition

UNIX standards ensure compatibility among UNIX-based operating systems.

Major Standards

POSIX
Portable Operating System Interface

Provides standard APIs for applications.

SUS

Single UNIX Specification

Defines UNIX operating system behavior.

IEEE Standards

Maintain portability across UNIX platforms.

Advantages

 Software portability
 Compatibility
 Standard programming interface

� 64-bit Architecture
⭐ Frequently Asked

Definition

A 64-bit Architecture uses 64-bit processors capable of processing 64 bits of data in one
instruction.
Architecture Diagram
Application

Operating System

64-bit CPU

Memory

Features

 Larger memory support


 Faster computation
 More registers
 Better multitasking
 Higher performance

Advantages

 Supports more than 4 GB RAM


 High-speed processing
 Better application performance

Transport Layer Protocols


The Transport Layer provides end-to-end communication.

Three important protocols:

 TCP
 UDP
 SCTP
TCP (Transmission Control Protocol)
Features

 Connection-oriented
 Reliable
 Ordered delivery
 Flow control
 Congestion control

Applications:

 HTTP
 FTP
 Email

UDP (User Datagram Protocol)


Features

 Connectionless
 Fast
 No acknowledgments
 Low overhead

Applications:

 Video Streaming
 VoIP
 DNS

SCTP (Stream Control Transmission


Protocol)
⭐ Important
Definition

SCTP is a transport layer protocol that combines the reliability of TCP with the message-oriented
nature of UDP.

Features

 Reliable communication
 Multi-streaming
 Multi-homing
 Congestion control
 Ordered delivery

Applications

 Telecom signaling
 VoIP
 Multimedia
 Banking systems

Comparison: TCP vs UDP vs SCTP


Feature TCP UDP SCTP

Connection Connection-Oriented Connectionless Connection-Oriented

Reliability Yes No Yes

Flow Control Yes No Yes

Congestion Control Yes No Yes

Ordered Delivery Yes No Yes

Multi-streaming No No Yes

Speed Medium High Medium


✅ Module 1 Complete.

🌐 NETWORK PROGRAMMING
(MSCS203)
MODULE 2 – Socket Programming
Syllabus:
Socket Introduction, Socket Address Structures, Value-Result Arguments, Byte Ordering &
Manipulation Functions, Address Conversion Functions, Elementary TCP Sockets (socket(),
connect(), bind(), listen(), accept()), fork() and Concurrent Server Design, getsockname(),
getpeername(), TCP Client/Server Example.

� Important Questions (Module 2)


Prepare these first (Most Expected VTU Questions):

1. Explain Socket Address Structures with neat diagram.


2. Explain Byte Ordering and Manipulation Functions.
3. Explain Address Conversion Functions.
4. Explain socket(), bind(), listen(), accept(), connect() functions.
5. Explain TCP Socket Programming with neat diagram.
6. Explain fork() and Concurrent Server Design.
7. Explain getsockname() and getpeername().
8. Explain TCP Client–Server Program.

� Introduction to Sockets
⭐ Very Important Question
Definition

A Socket is an endpoint of communication between two processes over a network. It acts as an


interface between the application and the transport layer (TCP/UDP).

A socket is identified by:

 IP Address
 Port Number
 Protocol (TCP/UDP)

Socket Architecture
Client Process
|
Socket API
|
TCP / UDP Layer
|
Internet (IP)
|
TCP / UDP Layer
|
Socket API
|
Server Process

Socket Types

1. Stream Socket (SOCK_STREAM)

 Uses TCP
 Reliable
 Connection-oriented

Example:

 HTTP
 FTP

2. Datagram Socket (SOCK_DGRAM)

 Uses UDP
 Connectionless
 Faster

Example:

 DNS
 Video Streaming

Advantages

 Reliable communication
 Supports multiple protocols
 Platform independent
 Easy to program

Socket Address Structure


⭐ Most Repeated Question

Definition

A Socket Address Structure stores the address information required for communication.

In C, the IPv4 socket address structure is:

struct sockaddr_in
{
short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};

Diagram
+----------------------+
| Address Family |
+----------------------+
| Port Number |
+----------------------+
| IP Address |
+----------------------+
| Padding |
+----------------------+
Fields

sin_family

Address family

Example:

AF_INET

sin_port

Stores port number

Example:

80

8080

443

sin_addr

Stores IPv4 address.

Example:

[Link]

sin_zero

Padding bytes.

Value–Result Arguments
Definition

Some socket functions use parameters that act as both:

 Input values
 Output values

These are called Value–Result Arguments.

Example
accept(sockfd,
(struct sockaddr *)&cliaddr,
&len);

Before function:

len = size of structure

After function:

len = actual size returned

Advantages

 Saves memory
 Efficient parameter passing

Byte Ordering
⭐ Frequently Asked

Definition

Computers store data differently.

To ensure correct communication, network protocols use Network Byte Order (Big Endian).
Types

Big Endian

Most significant byte first.

Example

12 34

Little Endian

Least significant byte first.

34 12

Diagram
Value = 0x1234

Big Endian

12 → 34

Little Endian

34 → 12

Byte Manipulation Functions


htons()

Host To Network Short

Converts 16-bit values.

htonl()

Host To Network Long

Converts 32-bit values.


ntohs()

Network To Host Short

ntohl()

Network To Host Long

Example
port = htons(8080);

Address Conversion Functions


⭐ Very Important

Used to convert between text and binary IP addresses.

inet_pton()

Presentation → Network

inet_pton(AF_INET,
"[Link]",
&addr);

inet_ntop()

Network → Presentation

inet_ntop(AF_INET,
&addr,
buffer,
sizeof(buffer));
Advantages

 Supports IPv4
 Supports IPv6
 Safer than older functions

Elementary TCP Socket Functions


⭐ Most Important Question

socket()

Creates a socket.

Syntax

socket(AF_INET,
SOCK_STREAM,
0);

bind()

Associates IP address and port number.

Syntax

bind(sockfd,
address,
sizeof(address));

listen()

Makes server ready to accept clients.

Syntax

listen(sockfd,
backlog);
accept()

Accepts incoming client connection.

Syntax

accept(sockfd,
NULL,
NULL);

connect()

Client connects to server.

Syntax

connect(sockfd,
address,
sizeof(address));

TCP Socket Flow Diagram


SERVER CLIENT

socket() socket()

bind()

listen()

connect()

accept()

Data Exchange

close()

fork() Function
⭐ Frequently Asked
Definition

fork() creates a new child process.

The child process executes concurrently with the parent.

Diagram
Parent

fork()

Parent Child

Advantages

 Concurrent processing
 Better server performance

Applications

 Concurrent Servers
 Process Creation

Concurrent Server Design


⭐ Very Important

Definition

A Concurrent Server serves multiple clients simultaneously.

Each client is handled by a separate process or thread.


Diagram
Server

----------------------------

| | |

Client1 Client2 Client3

Advantages

 Multiple users
 Better performance
 Reduced waiting time

� getsockname()
Definition

Returns the local socket address associated with a socket.

Syntax

getsockname(sockfd,
addr,
len);

Uses

 Find local IP
 Find local port

getpeername()
Definition

Returns the remote client's address.


Syntax

getpeername(sockfd,
addr,
len);

Uses

 Client identification
 Logging
 Security

TCP Client–Server Example


⭐ Most Expected Question

Server Steps

1. socket()
2. bind()
3. listen()
4. accept()
5. read()
6. write()
7. close()

Client Steps

1. socket()
2. connect()
3. write()
4. read()
5. close()

Complete Flow Diagram


CLIENT SERVER
socket() socket()

bind()

listen()

connect()

accept()

write() ---------------------->

read()

process

read() <----------------------

write()

close() close()

� Comparison: TCP vs UDP Socket


TCP Socket UDP Socket

SOCK_STREAM SOCK_DGRAM

Reliable Unreliable

Connection-Oriented Connectionless

Ordered Delivery No Ordering

Flow Control No Flow Control

✅ Module 2 Complete.

🌐 NETWORK PROGRAMMING
(MSCS203)
MODULE 3 – I/O Multiplexing and Socket
Options
Syllabus:
I/O Multiplexing, I/O Models, select() Function, str_cli() Function, Batch Input and Buffering,
shutdown() Function, TCP Echo Server, pselect() Function, poll() Function.

� Important Questions (Module 3)


Prepare these first (Highest Probability):

1. Explain I/O Models in Network Programming.


2. Explain I/O Multiplexing with neat diagram.
3. Explain the select() function with example.
4. Explain the pselect() function.
5. Explain the poll() function.
6. Compare select() and poll().
7. Explain the shutdown() function.
8. Explain TCP Echo Server.
9. Explain Batch Input and Buffering.
10. Explain str_cli() function.

� I/O Models in Network Programming


⭐ Most Repeated Question

Definition

An I/O Model defines how an application waits for data from sockets or devices. It determines
whether a process blocks, polls, or is notified when I/O is ready.

Types of I/O Models

1. Blocking I/O

 Process waits until data is available.


 Simplest model.
 CPU remains idle while waiting.

2. Non-Blocking I/O

 Process immediately returns if data is unavailable.


 Application repeatedly checks (polls).

3. I/O Multiplexing

 One process monitors multiple sockets simultaneously.


 Uses select() or poll().

4. Signal-Driven I/O

 OS sends a signal when data is ready.


 Process need not poll continuously.

5. Asynchronous I/O

 Process continues execution.


 OS performs I/O in the background.
 Notification is sent after completion.

I/O Models Diagram


I/O Models
|
-------------------------------------------------
| | | | |
Blocking Non-Blocking Multiplexing Signal Async
Driven I/O

Advantages

 Efficient CPU utilization


 Supports multiple clients
 Faster processing
 Reduced waiting time

� I/O Multiplexing
⭐ Very Important Question

Definition

I/O Multiplexing allows a single process to monitor multiple sockets and determine which
socket is ready for reading or writing.

It avoids creating one process for every client.

Working

1. Multiple sockets are registered.


2. select() or poll() monitors them.
3. OS reports ready sockets.
4. Process handles only active sockets.

Diagram
Client 1
|
Socket 1
|
|
Client2 -- Socket2 ----\
\
Client3 -- Socket3 -----> select()/poll()
/
Client4 -- Socket4 -----/
|
Server Process

Advantages

 One process handles many clients


 Efficient CPU usage
 Reduced memory consumption
 High scalability

select() Function
⭐ Most Expected VTU Question

Definition

The select() function monitors multiple file descriptors (sockets) and returns when one or more
become ready.

Syntax
int select(
int maxfd,
fd_set *readfds,
fd_set *writefds,
fd_set *exceptfds,
struct timeval *timeout
);

Parameters

 maxfd – Highest file descriptor + 1


 readfds – Read sockets
 writefds – Write sockets
 exceptfds – Exception sockets
 timeout – Waiting time

Working

1. Create socket list.


2. Add sockets using FD_SET().
3. Call select().
4. Check ready sockets using FD_ISSET().
5. Read/write data.
Diagram
Socket1

Socket2

Socket3

FD_SET()

select()

Ready Socket

Process Data

Advantages

 Multiple client support


 Simple API
 Good for small to medium applications

Disadvantages

 Limited number of file descriptors


 Inefficient for very large servers

pselect() Function
Definition

pselect() is an improved version of select() that provides safer signal handling.


Advantages

 Better signal handling


 Avoids race conditions
 More reliable than select()

Difference
select() pselect()

Older API Improved API

Basic timeout Precise timeout

Signal issues Better signal handling

� poll() Function
⭐ Very Important Question

Definition

The poll() function monitors multiple file descriptors like select(), but without the descriptor
limit.

Syntax
int poll(
struct pollfd fds[],
nfds_t nfds,
int timeout
);

Working

1. Create pollfd array.


2. Register sockets.
3. Call poll().
4. Check events.
5. Process ready sockets.
Diagram
Sockets

pollfd Array

poll()

Ready Socket

Server

Advantages

 No descriptor limit
 Better scalability
 Efficient for large servers

Disadvantages

 Slightly more complex than select()

Comparison: select() vs poll()


⭐ Frequently Asked

select() poll()

Uses fd_set Uses pollfd array

Descriptor limit No descriptor limit

Slower for many sockets Better scalability


select() poll()

Simple More efficient

Widely supported Modern API

shutdown() Function
⭐ Important Question

Definition

The shutdown() function closes part or all of a TCP connection without immediately releasing
the socket.

Syntax
shutdown(sockfd, how);

Modes

SHUT_RD

Disable receiving.

SHUT_WR

Disable sending.

SHUT_RDWR

Disable both sending and receiving.


Diagram
Client ---- TCP Connection ---- Server

shutdown()

Read Disabled

or

Write Disabled

Advantages

 Graceful connection closing


 Better resource management

Batch Input and Buffering


Definition

Instead of sending one byte at a time, multiple bytes are grouped into a buffer before
transmission.

Diagram
Application

Buffer

TCP

Network

Advantages

 Better throughput
 Reduced overhead
 Faster communication

� str_cli() Function
Definition

str_cli() is a client-side function used in Stevens' examples to communicate with a TCP


server.

Working

1. Read user input.


2. Send data to server.
3. Receive server response.
4. Display output.
5. Repeat.

Flow Diagram
Keyboard

str_cli()

TCP Socket

Server

Response

Display
� TCP Echo Server
⭐ Most Expected Question

Definition

A TCP Echo Server receives data from a client and sends the same data back.

Working

Server

1. socket()
2. bind()
3. listen()
4. accept()
5. read()
6. write()
7. close()

Client

1. socket()
2. connect()
3. write()
4. read()
5. close()

TCP Echo Server Diagram


CLIENT SERVER

socket() socket()

connect() bind()

write() -----------------> listen()

accept()

read()
write()

read() <----------------

close() close()

Applications

 Network testing
 Socket debugging
 Learning TCP programming

✅ Module 3 Complete.

🌐 NETWORK PROGRAMMING
(MSCS203)
MODULE 4 – Advanced I/O Functions &
UNIX Domain Protocols
Syllabus:
Advanced I/O Functions – Socket Timeouts, recv(), send(), readv(), writev(), sendmsg(),
recvmsg(), UNIX Domain Protocols, Socket Address Structure, socketpair(), UNIX Domain
Stream Client/Server, UNIX Domain Datagram Client/Server.

� Important Questions (Module 4)


Prepare these first (Highest Probability):

1. Explain Advanced I/O Functions in Network Programming.


2. Explain recv() and send() functions.
3. Explain readv() and writev().
4. Explain sendmsg() and recvmsg().
5. Explain Socket Timeouts.
6. Explain UNIX Domain Protocols.
7. Explain UNIX Domain Socket Address Structure.
8. Explain socketpair() function.
9. Explain UNIX Domain Stream Client–Server.
10. Explain UNIX Domain Datagram Client–Server.

Advanced I/O Functions


⭐ Most Expected Question

Definition

Advanced I/O functions provide efficient communication between processes by allowing


multiple buffers, message passing, timeout handling, and local IPC (Inter Process
Communication).

These functions improve performance and flexibility compared to basic read() and write().

Types of Advanced I/O Functions

 recv()
 send()
 readv()
 writev()
 recvmsg()
 sendmsg()
 socketpair()
 Socket Timeouts

Diagram
Application

Advanced I/O API

┌────────────────────────────┐
│ recv() send() │
│ readv() writev() │
│ recvmsg() sendmsg() │
│ socketpair() │
└────────────────────────────┘

TCP / UDP

Advantages

 High-speed communication
 Multiple buffer support
 Message-oriented communication
 Better performance
 Efficient resource utilization

recv() Function
⭐ Frequently Asked

Definition

The recv() function receives data from a connected socket.

Syntax
recv(sockfd, buffer, size, flags);

Parameters

 sockfd → Socket Descriptor


 buffer → Storage Area
 size → Number of Bytes
 flags → Control Options

Working
Server

recv()


Buffer

Application

Advantages

 Reliable data reception


 Flexible flags
 Easy to use

send() Function
Definition

The send() function transmits data through a connected socket.

Syntax
send(sockfd, buffer, size, flags);

Working
Application

send()

Socket

Network

Advantages

 Reliable transmission
 Fast communication
 Simple interface

� Difference Between recv() and send()


recv() send()

Receives data Sends data

Server/Client Server/Client

Reads from socket Writes to socket

Input Function Output Function

readv() Function
⭐ Important

Definition

readv() reads data into multiple buffers using a single system call.

Diagram
Network Data

readv()

Buffer 1

Buffer 2

Buffer 3
Advantages

 Faster than multiple read()


 Less CPU overhead
 Efficient memory usage

writev() Function
Definition

writev() writes data from multiple buffers in a single operation.

Diagram
Buffer1

Buffer2

Buffer3

writev()

Socket

Advantages

 Single system call


 Improved performance
 Reduced context switching

� readv() vs writev()
readv() writev()

Reads data Writes data


readv() writev()

Multiple buffers Multiple buffers

Input Output

recvmsg() Function
⭐ Frequently Asked

Definition

recvmsg() receives messages and additional control information such as file descriptors and
socket options.

Syntax
recvmsg(sockfd,
&msg,
flags);

Uses

 Receive file descriptors


 Receive control messages
 UNIX Domain Communication

sendmsg() Function
Definition

sendmsg() sends structured messages with optional control information.

Diagram
Application

sendmsg()

Socket

Network

Advantages

 Message passing
 Control information support
 UNIX IPC

� sendmsg() vs recvmsg()
sendmsg() recvmsg()

Sends message Receives message

Output Input

Control data Control data

Socket Timeouts
⭐ Very Important

Definition

Socket timeout specifies the maximum waiting time for sending or receiving data.

If the timeout expires, the operation fails instead of waiting forever.


Diagram
Request Sent

Waiting

Timeout?

Yes → Error

No → Receive Data

Advantages

 Prevents infinite waiting


 Better application control
 Improves reliability

UNIX Domain Protocols


⭐ Most Expected Question

Definition

UNIX Domain Protocols provide communication between processes running on the same
machine without using network hardware.

Advantages

 Very Fast
 Reliable
 Secure
 Low latency
Diagram
Process A

UNIX Socket

Kernel

UNIX Socket

Process B

Applications

 Database Servers
 Web Servers
 IPC
 Local Applications

� UNIX Domain Socket Address Structure


Definition

UNIX Domain sockets use pathname-based addresses instead of IP addresses.

Structure
struct sockaddr_un
{
sa_family_t sun_family;
char sun_path[108];
};

Fields

sun_family
AF_UNIX

sun_path

Stores socket file path.

Example

/tmp/socket

socketpair() Function
⭐ Important

Definition

Creates two connected sockets for local communication.

Syntax
socketpair(AF_UNIX,
SOCK_STREAM,
0,
sockfd);

Diagram
Socket A

Socket B

Advantages

 Fast IPC
 No network required
 Full duplex communication
UNIX Domain Stream Client–Server
Definition

Uses SOCK_STREAM.

Connection-oriented.

Reliable communication.

Diagram
Client

Stream Socket

Server

Features

 Reliable
 Ordered
 Connection-oriented

UNIX Domain Datagram Client–Server


Definition

Uses SOCK_DGRAM.

Connectionless communication.

Diagram
Client


Datagram Socket

Server

Features

 Faster
 Connectionless
 No delivery guarantee

� Comparison: UNIX Stream vs UNIX


Datagram
Stream Datagram

SOCK_STREAM SOCK_DGRAM

Reliable Unreliable

Connection-oriented Connectionless

Ordered Unordered

✅ Module 4 Complete.
NETWORK PROGRAMMING (MSCS203)
MODULE 5 – Client/Server Design
Alternatives
Syllabus:
TCP Client Alternatives, TCP Test Client, TCP Iterative Server, TCP Concurrent Server, TCP
Preforked Server, No Locking Around accept(), File Locking Around accept(), Thread Locking
Around accept(), Descriptor Passing, One Thread Per Client.

� Important Questions (Module 5)


Prepare these first (Highest Probability):

1. Explain TCP Iterative Server.


2. Explain TCP Concurrent Server.
3. Compare Iterative Server and Concurrent Server.
4. Explain TCP Preforked Server.
5. Explain No Locking Around accept().
6. Explain File Locking Around accept().
7. Explain Thread Locking Around accept().
8. Explain Descriptor Passing.
9. Explain One Thread Per Client Model.
10. Explain TCP Test Client.

� Client–Server Design Alternatives


⭐ Most Expected Question

Definition

Client–Server Design Alternatives are different techniques used to design TCP servers for
handling one or multiple client requests efficiently.

Depending on the application, a server may serve:

 One client at a time


 Multiple clients simultaneously
 Multiple clients using processes
 Multiple clients using threads

Design Alternatives

 Iterative Server
 Concurrent Server
 Preforked Server
 Multithreaded Server

Diagram
Server

-----------------------

| | | |

Iterative Concurrent Prefork Threaded

Advantages

 Better scalability
 High performance
 Multiple client support
 Efficient resource utilization

� TCP Client Alternatives


Definition

A TCP client can communicate with the server using different approaches depending on the
application.

Types

Simple Client
One request → One response.

Interactive Client

Multiple requests and responses.

Batch Client

Sends multiple requests together.

Test Client

Used to test server performance.

Applications

 Browser
 FTP Client
 Banking Application
 Chat Application

� TCP Test Client


Definition

A TCP Test Client is used to verify whether a TCP server is functioning correctly.

It connects to the server, sends test data, and checks the received response.

Working

1. Create socket.
2. Connect to server.
3. Send test message.
4. Receive response.
5. Close connection.

Diagram
Test Client

TCP Connection

Server

Response

Advantages

 Server testing
 Debugging
 Performance evaluation

� TCP Iterative Server


⭐ Most Repeated VTU Question

Definition

An Iterative Server serves one client at a time.

The next client waits until the current client finishes.

Working

1. socket()
2. bind()
3. listen()
4. accept()
5. Serve client
6. Close connection
7. Accept next client

Diagram
Client1 ----->

Server

Client2 (Waiting)

Client3 (Waiting)

Advantages

 Simple
 Easy implementation
 Low memory usage

Disadvantages

 Poor performance
 Long waiting time
 Cannot serve multiple users simultaneously

� TCP Concurrent Server


⭐ Most Expected Question

Definition

A Concurrent Server serves multiple clients simultaneously.

Each client is handled by a separate process or thread.


Working

1. accept() client.
2. fork() or create thread.
3. Child handles client.
4. Parent waits for next client.

Diagram
Server

--------------------------------

| | |

Client1 Client2 Client3

Advantages

 Multiple users
 Better performance
 Faster response
 High throughput

Disadvantages

 Higher memory usage


 More complex implementation

Comparison: Iterative vs Concurrent Server


Iterative Concurrent

One client Multiple clients

Slow Fast
Iterative Concurrent

Simple Complex

Low memory Higher memory

Low throughput High throughput

� TCP Preforked Server


⭐ Frequently Asked

Definition

A Preforked Server creates multiple child processes before any client connects.

When a client arrives, one idle child serves the client.

Diagram
Parent

-----------------------------

| | |

Child1 Child2 Child3

Clients

Advantages

 Fast client servicing


 No fork delay
 Better scalability
Disadvantages

 Higher memory usage


 Idle child processes consume resources

� No Locking Around accept()


Definition

All child processes call accept() simultaneously without synchronization.

Problem

Multiple child processes compete for the same connection.

This is called the Thundering Herd Problem.

Diagram
Client

accept()

Child1

Child2

Child3

(All waiting)

Disadvantages

 CPU wastage
 Resource contention
 Performance degradation
� File Locking Around accept()
Definition

A file lock ensures that only one child process executes accept() at a time.

Working

1. Acquire lock.
2. Call accept().
3. Release lock.
4. Next process acquires lock.

Diagram
Lock

accept()

Unlock

Advantages

 Prevents race conditions


 Eliminates thundering herd
 Reliable synchronization

Disadvantages

 Lock overhead
 Slight delay
� Thread Locking Around accept()
Definition

A mutex lock is used to synchronize threads before calling accept().

Diagram
Mutex Lock

accept()

Mutex Unlock

Advantages

 Better than file locking


 Fast synchronization
 Low overhead

� Descriptor Passing
⭐ Very Important Question

Definition

Descriptor Passing allows one process to send an open file descriptor (socket descriptor) to
another process using UNIX domain sockets.

Working

1. Parent accepts client.


2. Parent sends descriptor.
3. Child receives descriptor.
4. Child communicates with client.
Diagram
Parent Process

Socket Descriptor

UNIX Socket

Child Process

Advantages

 Efficient communication
 Resource sharing
 Used in preforked servers

1 � One Thread Per Client Model


⭐ Frequently Asked

Definition

Each client connection is handled by a separate thread.

Working

1. Client connects.
2. Server creates thread.
3. Thread serves client.
4. Thread terminates.

Diagram
Server
|

--------------------------------

| | |

Thread1 Thread2 Thread3

| | |

Client1 Client2 Client3

Advantages

 Fast response
 Shared memory
 Low process creation cost
 Better scalability

Disadvantages

 Thread synchronization required


 Complex programming

� Comparison: Preforked Server vs One


Thread Per Client
Preforked Server One Thread Per Client

Uses Processes Uses Threads

Higher Memory Lower Memory

Slower Context Switch Faster Context Switch

Better Isolation Shared Memory

More Overhead Less Overhead

You might also like