Network Programming
Network Programming
� MODULE 1 – Introduction
Explain the OSI Model with neat diagram.
� MODULE 2 – Sockets
� Explain Socket Address Structures.
socket()
bind()
listen()
accept()
connect()
⭐ 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 is the process of writing programs that communicate with other
programs over a computer network using protocols like TCP/IP, UDP, and SCTP.
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
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
� 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.
1. Physical Layer
Transmits bits
Defines cables and connectors
Examples:
Ethernet Cable
Optical Fiber
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
Examples:
HTTP
FTP
SMTP
DNS
Advantages
Standard architecture
Easy troubleshooting
Modular design
Interoperability
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
Importance
Examples:
Hosts
Examples:
Computer
Server
Laptop
Smartphone
Loopback Address
[Link]
UNIX Standards
Definition
Major Standards
POSIX
Portable Operating System Interface
SUS
IEEE Standards
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
Advantages
TCP
UDP
SCTP
TCP (Transmission Control Protocol)
Features
Connection-oriented
Reliable
Ordered delivery
Flow control
Congestion control
Applications:
HTTP
FTP
Email
Connectionless
Fast
No acknowledgments
Low overhead
Applications:
Video Streaming
VoIP
DNS
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
Multi-streaming No No Yes
🌐 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.
� Introduction to Sockets
⭐ Very Important Question
Definition
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
Uses TCP
Reliable
Connection-oriented
Example:
HTTP
FTP
Uses UDP
Connectionless
Faster
Example:
DNS
Video Streaming
Advantages
Reliable communication
Supports multiple protocols
Platform independent
Easy to program
Definition
A Socket Address Structure stores the address information required for communication.
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
Example:
80
8080
443
sin_addr
Example:
[Link]
sin_zero
Padding bytes.
Value–Result Arguments
Definition
Input values
Output values
Example
accept(sockfd,
(struct sockaddr *)&cliaddr,
&len);
Before function:
After function:
Advantages
Saves memory
Efficient parameter passing
Byte Ordering
⭐ Frequently Asked
Definition
To ensure correct communication, network protocols use Network Byte Order (Big Endian).
Types
Big Endian
Example
12 34
Little Endian
34 12
Diagram
Value = 0x1234
Big Endian
12 → 34
Little Endian
34 → 12
htonl()
ntohl()
Example
port = htons(8080);
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
socket()
Creates a socket.
Syntax
socket(AF_INET,
SOCK_STREAM,
0);
bind()
Syntax
bind(sockfd,
address,
sizeof(address));
listen()
Syntax
listen(sockfd,
backlog);
accept()
Syntax
accept(sockfd,
NULL,
NULL);
connect()
Syntax
connect(sockfd,
address,
sizeof(address));
socket() socket()
bind()
listen()
connect()
accept()
Data Exchange
close()
fork() Function
⭐ Frequently Asked
Definition
Diagram
Parent
fork()
Parent Child
Advantages
Concurrent processing
Better server performance
Applications
Concurrent Servers
Process Creation
Definition
----------------------------
| | |
Advantages
Multiple users
Better performance
Reduced waiting time
� getsockname()
Definition
Syntax
getsockname(sockfd,
addr,
len);
Uses
Find local IP
Find local port
getpeername()
Definition
getpeername(sockfd,
addr,
len);
Uses
Client identification
Logging
Security
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()
bind()
listen()
connect()
accept()
write() ---------------------->
read()
process
read() <----------------------
write()
close() close()
SOCK_STREAM SOCK_DGRAM
Reliable Unreliable
Connection-Oriented Connectionless
✅ 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.
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.
1. Blocking I/O
2. Non-Blocking I/O
3. I/O Multiplexing
4. Signal-Driven I/O
5. Asynchronous I/O
Advantages
� 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.
Working
Diagram
Client 1
|
Socket 1
|
|
Client2 -- Socket2 ----\
\
Client3 -- Socket3 -----> select()/poll()
/
Client4 -- Socket4 -----/
|
Server Process
Advantages
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
Working
Socket2
Socket3
FD_SET()
select()
Ready Socket
Process Data
Advantages
Disadvantages
pselect() Function
Definition
Difference
select() pselect()
� 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
pollfd Array
poll()
Ready Socket
Server
Advantages
No descriptor limit
Better scalability
Efficient for large servers
Disadvantages
select() poll()
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
shutdown()
Read Disabled
or
Write Disabled
Advantages
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
Working
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()
socket() socket()
connect() bind()
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.
Definition
These functions improve performance and flexibility compared to basic read() and write().
recv()
send()
readv()
writev()
recvmsg()
sendmsg()
socketpair()
Socket Timeouts
Diagram
Application
┌────────────────────────────┐
│ 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
Syntax
recv(sockfd, buffer, size, flags);
Parameters
Working
Server
recv()
↓
Buffer
Application
Advantages
send() Function
Definition
Syntax
send(sockfd, buffer, size, flags);
Working
Application
send()
Socket
Network
Advantages
Reliable transmission
Fast communication
Simple interface
Server/Client Server/Client
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
writev() Function
Definition
Diagram
Buffer1
Buffer2
Buffer3
writev()
Socket
Advantages
� readv() vs writev()
readv() writev()
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
sendmsg() Function
Definition
Diagram
Application
↓
sendmsg()
Socket
Network
Advantages
Message passing
Control information support
UNIX IPC
� sendmsg() vs recvmsg()
sendmsg() recvmsg()
Output Input
Socket Timeouts
⭐ Very Important
Definition
Socket timeout specifies the maximum waiting time for sending or receiving data.
Waiting
Timeout?
Yes → Error
No → Receive Data
Advantages
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
Structure
struct sockaddr_un
{
sa_family_t sun_family;
char sun_path[108];
};
Fields
sun_family
AF_UNIX
sun_path
Example
/tmp/socket
socketpair() Function
⭐ Important
Definition
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
Uses SOCK_DGRAM.
Connectionless communication.
Diagram
Client
↓
Datagram Socket
Server
Features
Faster
Connectionless
No delivery guarantee
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.
Definition
Client–Server Design Alternatives are different techniques used to design TCP servers for
handling one or multiple client requests efficiently.
Design Alternatives
Iterative Server
Concurrent Server
Preforked Server
Multithreaded Server
Diagram
Server
-----------------------
| | | |
Advantages
Better scalability
High performance
Multiple client support
Efficient resource utilization
A TCP client can communicate with the server using different approaches depending on the
application.
Types
Simple Client
One request → One response.
Interactive Client
Batch Client
Test Client
Applications
Browser
FTP Client
Banking Application
Chat Application
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
Definition
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
Definition
1. accept() client.
2. fork() or create thread.
3. Child handles client.
4. Parent waits for next client.
Diagram
Server
--------------------------------
| | |
Advantages
Multiple users
Better performance
Faster response
High throughput
Disadvantages
Slow Fast
Iterative Concurrent
Simple Complex
Definition
A Preforked Server creates multiple child processes before any client connects.
Diagram
Parent
-----------------------------
| | |
Clients
Advantages
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
Disadvantages
Lock overhead
Slight delay
� Thread Locking Around accept()
Definition
Diagram
Mutex Lock
accept()
Mutex Unlock
Advantages
� 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
Socket Descriptor
UNIX Socket
Child Process
Advantages
Efficient communication
Resource sharing
Used in preforked servers
Definition
Working
1. Client connects.
2. Server creates thread.
3. Thread serves client.
4. Thread terminates.
Diagram
Server
|
--------------------------------
| | |
| | |
Advantages
Fast response
Shared memory
Low process creation cost
Better scalability
Disadvantages