0% found this document useful (0 votes)
4 views19 pages

Module1 - Module2 - QBank - KeyAnswer

The document is a question bank for the Network Programming course (MSCS203) for M.Tech 2nd Semester, covering various topics related to network programming, including the OSI model, client-server paradigm, BSD networking history, and comparisons of TCP, UDP, and SCTP protocols. Each module contains questions with specified marks, Bloom's levels, and course outcomes, along with detailed answers for key concepts. It serves as a comprehensive resource for students to prepare for examinations and understand fundamental networking principles.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Module1 - Module2 - QBank - KeyAnswer

The document is a question bank for the Network Programming course (MSCS203) for M.Tech 2nd Semester, covering various topics related to network programming, including the OSI model, client-server paradigm, BSD networking history, and comparisons of TCP, UDP, and SCTP protocols. Each module contains questions with specified marks, Bloom's levels, and course outcomes, along with detailed answers for key concepts. It serves as a comprehensive resource for students to prepare for examinations and understand fundamental networking principles.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Network Programming (MSCS203) | M.

Tech 2nd Semester | Question Bank

NETWORK PROGRAMMING
MSCS203 | Second Semester [Link] | CBCS Scheme
Module-Wise Question Bank with Answers
Reference: UNIX Network Programming, Vol. 1 – W. Richard Stevens, Bill Fenner, Andrew M. Rudoff (3rd Ed.)
M = Marks | L = Bloom's Level | CO = Course Outcome

MODULE 1 – Question Bank


Based on: Chapter 1 (Introduction) and Chapter 2 (Transport Layer: TCP, UDP, and SCTP)

[Link] Questions M L CO

1 Explain the OSI Reference Model with a neat diagram. Discuss the functions 10 2 CO1
of each layer and justify how it provides a standardized framework for
network communication.

2 Discuss the client-server paradigm in network programming. Explain the 10 2 CO1


roles of client and server with suitable real-time examples and illustrate the
interaction process.

3 Explain the history and evolution of BSD networking. Discuss its contribution 10 2 CO1
to modern socket programming and networking APIs.

4 Compare the OSI model and TCP/IP model in terms of architecture, 10 3 CO1
functionality, and practical implementation. Highlight key differences with a
suitable diagram.

5 Explain the basic functions of sockets in network programming. Discuss how 6 2 CO1
sockets enable inter-process communication over a network.

6 Explain the working of client-server communication using TCP sockets. 10 3 CO1


Illustrate the sequence of system calls involved with a suitable diagram.

7 Discuss the Unix standards for 64-bit architectures. Explain their 10 3 CO1
significance in modern network programming environments.

8 Write detailed notes on TCP, UDP, and SCTP protocols. Compare them 10 3 CO1
based on reliability, connection type, and applications.

9 Explain the three-way handshake mechanism in TCP connection 6 2 CO1


establishment and four-way handshake for termination with neat diagrams.

10 Analyze the advantages and limitations of the client-server model in 10 4 CO1


distributed systems. Suggest scenarios where it may not be suitable.

11 Evaluate the performance differences between TCP and UDP protocols 10 4 CO1
under various network conditions such as congestion and real-time
communication.

12 Explain how data flows through OSI layers during a typical client-server 6 3 CO1
communication.

13 Discuss the TIME_WAIT state in TCP. Why is it necessary? Explain its 6 2 CO1
duration and the two reasons for its existence.

14 Explain port numbers, their ranges, and their significance in TCP connection 10 3 CO1
handling with concurrent servers.

15 Critically evaluate the relevance of the OSI model in modern networking 10 4 CO1

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 1
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

[Link] Questions M L CO

systems. Is it still applicable? Justify your answer.

MODULE 1 – Detailed Answers

Q1. OSI Reference Model (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO1
Reference: Chapter 1, Section 1.7 (Stevens UNP Vol.1)
Answer:
The OSI (Open Systems Interconnection) model, defined by ISO, is a 7-layer framework for network communication
(Stevens, Section 1.7).

Layer 7 – Application: Provides network services directly to user applications (HTTP, FTP, SMTP).
Layer 6 – Presentation: Handles data translation, encryption, compression (e.g., JPEG, TLS).
Layer 5 – Session: Manages sessions between applications; establishes, maintains, terminates connections.
Layer 4 – Transport: Provides end-to-end communication; TCP (reliable) and UDP (unreliable) operate here.
Layer 3 – Network: Handles routing and logical addressing; IPv4 and IPv6 operate here.
Layer 2 – Data Link: Provides node-to-node data transfer; frames data for physical transmission.
Layer 1 – Physical: Transmits raw bits over physical media.

Stevens notes: 'We consider the bottom two layers of the OSI model as the device driver and networking hardware.'
(Section 1.7)
Sockets API maps to Layers 5–7 (application, session, presentation), while TCP/IP handles layers 3–4.

Diagram: Application → Presentation → Session → Transport (TCP/UDP) → Network (IP) → Data Link → Physical

Q2. Client-Server Paradigm (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO1
Reference: Chapter 1, Section 1.1 (Stevens UNP Vol.1)
Answer:
Stevens (Section 1.1) defines the client-server model: a client initiates communication; a server responds.

Key roles:
CLIENT: Initiates requests, active role, communicates with one server at a time, usually short-lived.
SERVER: Long-running daemon, responds to requests, can handle multiple clients concurrently.

Stevens: 'Deciding that the client always initiates requests tends to simplify the protocol as well as the programs
themselves.' (Section 1.1)

Types of servers:
Iterative Server: Handles one client at a time (simple but inefficient).
Concurrent Server: Forks a child process or uses threads for each client (used in most real applications).

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 2
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Real-time examples:
Web server (Apache) → serves browser clients
FTP server → handles file transfer clients

Interaction diagram (from Figure 1.1 of Stevens):


client --[application protocol]--> server
Multiple clients connect to a single server concurrently (Figure 1.2).

Q3. BSD Networking History (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO1
Reference: Chapter 1, Section 1.8 (Stevens UNP Vol.1)
Answer:
BSD (Berkeley Software Distribution) networking history is covered in Section 1.8 of Stevens.

Timeline:
1983 – 4.2BSD: First release of the socket API. Introduced socket(), bind(), connect(), accept(), listen().
1986 – 4.3BSD: Added sequence numbers to socket address structures.
1990 – 4.3BSD Reno: Added length field to socket address structures, POSIX compliance begun.
1993 – 4.4BSD: Mature socket API, still the foundation of modern networking.

Contributions:
BSD sockets became the standard network programming API adopted by POSIX.
Enabled portable network applications across Unix variants and other OSes.
Introduced the sockaddr generic address structure used to this day.

Stevens: BSD networking forms the foundation of the socket API used globally in Linux, macOS, Windows
(Winsock), and embedded systems.

Q4. OSI vs TCP/IP Model Comparison (10 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO1
Reference: Chapter 1, Section 1.7 (Stevens UNP Vol.1)
Answer:
OSI Model (7 layers): Application, Presentation, Session, Transport, Network, Data Link, Physical.
TCP/IP Model (4 layers): Application, Transport, Internet, Network Access.

Key differences:
Architecture: OSI has 7 layers; TCP/IP merges Session+Presentation+Application into one Application layer.
Design: OSI is a conceptual reference model; TCP/IP is an implementation-based model.
Transport: Both use TCP and UDP at transport layer.
Network: OSI uses 'Network' layer; TCP/IP uses 'Internet' layer (IPv4/IPv6).
Practical use: TCP/IP is widely used in the Internet; OSI is used as a teaching framework.

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 3
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Stevens (Section 1.7): 'The network layer is handled by the IPv4 and IPv6 protocols ... The transport layers that we
can choose from are TCP and UDP.'

Diagram (TCP/IP to OSI mapping):


TCP/IP Application ↔ OSI Application + Presentation + Session
TCP/IP Transport ↔ OSI Transport
TCP/IP Internet ↔ OSI Network
TCP/IP Network Access ↔ OSI Data Link + Physical

Q5. Sockets in Network Programming (6 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO1
Reference: Chapter 1, Sections 1.1–1.5 (Stevens UNP Vol.1)
Answer:
A socket is an endpoint for two-way communication between processes over a network.

Key socket functions (Stevens, Sections 1.2–1.5):


socket(): Creates a socket endpoint.
bind(): Associates a local address with the socket.
connect(): Connects client to a server address.
listen(): Marks socket as passive (server side).
accept(): Accepts incoming connection from client.
read()/write(): Data exchange.
close(): Closes the connection.

Sockets enable IPC (inter-process communication) across network by providing an abstraction over TCP/IP stack.

Q6. TCP Client-Server Communication with System Calls (10 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO1
Reference: Chapter 1, Section 1.2 & Chapter 4 (Stevens UNP Vol.1)
Answer:
TCP client-server involves a sequence of system calls (Stevens, Figure 4.1):

SERVER side:
1. socket() – Create TCP socket.
2. bind() – Bind to well-known port.
3. listen() – Mark as passive socket with backlog queue.
4. accept() – Block and wait for client connection.
5. read()/write() – Exchange data with client.
6. close() – Close connection.

CLIENT side:

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 4
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

1. socket() – Create TCP socket.


2. connect() – Trigger three-way handshake to server.
3. write()/read() – Send request, receive response.
4. close() – Initiate four-way termination.

Stevens (Section 1.2): The daytime client example illustrates this complete flow. The server uses port 13 and the
client connects, reads the date/time, and prints it.

Diagram: socket→bind→listen→accept [server] | socket→connect [client] → Data Transfer → close

Q7. Unix Standards and 64-bit Architectures (10 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO1
Reference: Chapter 1, Sections 1.10–1.11 (Stevens UNP Vol.1)
Answer:
Unix standards (Stevens, Section 1.10): POSIX 1003.1-2001 (also known as Single Unix Specification Version 3) is
the primary standard referenced in UNP 3rd edition.

Major Unix standards:


POSIX.1 (1988): Portable Operating System Interface – defines system calls, file I/O, processes.
XPG3/XPG4: X/Open Portability Guide – superset of POSIX, includes networking.
SUSv3: Single UNIX Specification Version 3 – unified POSIX + XPG4.

64-bit Architectures (Stevens, Section 1.11):


The LP64 model: long and pointers are 64-bit; int remains 32-bit.
Significance for sockets: socklen_t was introduced (previously just int) to ensure correct size.
Stevens: POSIX recommends socklen_t be defined as uint32_t.
Functions like accept(), getsockname() use socklen_t to correctly handle address length on 64-bit systems.

Impact: Without proper 64-bit awareness, pointers cast to integers can cause bugs in socket address handling.

Q8. TCP, UDP, and SCTP Comparison (10 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO1
Reference: Chapter 2, Sections 2.3–2.5 (Stevens UNP Vol.1)
Answer:
UDP – User Datagram Protocol (Section 2.3):
Connectionless, unreliable, no flow control or congestion control.
Each UDP datagram carries source/destination IP address and ports.
Application: DNS, SNMP, multimedia streaming, online gaming.

TCP – Transmission Control Protocol (Section 2.4):


Connection-oriented (3-way handshake), reliable (ACKs, retransmission), ordered delivery.
Full-duplex data flow, byte-stream service (no record boundaries).
Features: flow control (sliding window), congestion control.

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 5
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Application: HTTP, FTP, Telnet, email (SMTP, IMAP).

SCTP – Stream Control Transmission Protocol (Section 2.5):


Message-oriented, reliable, connection-oriented (association).
Supports multihoming (multiple IP addresses per endpoint).
Multiple streams within one association (avoids head-of-line blocking).
Application: VoIP signaling (SS7 over IP), telecom applications.

Comparison table: UDP=unreliable/no connection | TCP=reliable/connection |


SCTP=reliable/multi-stream/multihomed

Q9. TCP Three-Way Handshake (6 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO1
Reference: Chapter 2, Section 2.6 (Stevens UNP Vol.1)
Answer:
TCP Connection Establishment – Three-Way Handshake (Stevens, Section 2.6, Figure 2.2):

Step 1: Client sends SYN to server (SYN J, MSS option announced).


Step 2: Server responds with SYN+ACK (SYN K, ACK J+1).
Step 3: Client sends ACK (ACK K+1). Connection established.

After handshake: both sides are in ESTABLISHED state; data transfer begins.

TCP Connection Termination – Four-Way Handshake:


Step 1: Active close side sends FIN M.
Step 2: Passive close side sends ACK M+1.
Step 3: Passive close side sends FIN N.
Step 4: Active close side sends ACK N+1, enters TIME_WAIT state.

Stevens: Eight segments total for a simple request-reply using TCP vs. two for UDP (Section 2.6).

Q10. Client-Server Model: Advantages and Limitations (10 Marks)


Bloom's Level: L4 – Analyze
Course Outcome: CO1
Reference: Chapter 1, Section 1.1 (Stevens UNP Vol.1)
Answer:
Advantages of Client-Server Model (Stevens, Section 1.1):
Centralized resource management – server controls data and logic.
Scalability – concurrent server handles many clients.
Simplicity – clear protocol design with client initiating communication.
Security – access control enforced at server.

Limitations:

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 6
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Single point of failure – server crash affects all clients.


Scalability bottleneck under heavy load.
Server cost – requires always-on, high-availability infrastructure.
Not suitable for peer-to-peer scenarios (e.g., file sharing networks like BitTorrent).

Scenarios where unsuitable:


Large-scale peer-to-peer file sharing (P2P better).
Massively distributed real-time systems (publish-subscribe or actor model better).
Edge computing environments where latency to central server is unacceptable.

Q11. TCP vs UDP Performance Evaluation (10 Marks)


Bloom's Level: L4 – Analyze
Course Outcome: CO1
Reference: Chapter 2, Sections 2.3–2.4 (Stevens UNP Vol.1)
Answer:
Performance analysis under network conditions (Stevens, Sections 2.3–2.4):

Under Congestion:
TCP: Uses congestion control (slow start, congestion avoidance, fast retransmit). Reduces throughput to prevent
collapse.
UDP: No congestion control. Can worsen congestion; application must implement its own.

Under Real-time Communication:


TCP: Retransmission adds latency; head-of-line blocking; not suitable for real-time audio/video.
UDP: Low latency, preferred for real-time apps (VoIP, video streaming, gaming).

Reliability:
TCP: Guarantees delivery, ordering, error detection. 8 segments overhead for single request-reply (vs 2 for UDP).
UDP: Best-effort. Application handles reliability if needed (e.g., RTP over UDP).

Stevens: 'If UDP was used instead, only two packets would be exchanged...But switching from TCP to UDP
removes all the reliability.' (Section 2.6)

Conclusion: TCP preferred for data integrity; UDP preferred for low-latency real-time applications.

Q12. Data Flow through OSI Layers in Client-Server (6 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO1
Reference: Chapter 1, Section 1.7 (Stevens UNP Vol.1)
Answer:
When a client sends data to a server (Stevens, Section 1.7, Figure 1.14):

CLIENT SIDE (top-down encapsulation):


Application layer: Data created by app (e.g., HTTP GET request).
Transport layer: TCP/UDP adds port numbers, creates segment.

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 7
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Network layer: IP adds source/destination IP addresses, creates datagram.


Data Link layer: Adds MAC addresses, creates frame.
Physical layer: Transmits bits over wire/wireless.

SERVER SIDE (bottom-up de-encapsulation):


Physical → Data Link → Network → Transport → Application (reverse process).

Stevens: 'We consider the bottom two layers of the OSI model as the device driver and networking hardware.'
(Section 1.7)
Sockets API sits between the Application and Transport layers.

Q13. TIME_WAIT State in TCP (6 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO1
Reference: Chapter 2, Section 2.7 (Stevens UNP Vol.1)
Answer:
TIME_WAIT state is entered by the end that performs the active close (Stevens, Section 2.7).

Duration: 2 * MSL (Maximum Segment Lifetime). MSL is typically 30s–2 minutes → TIME_WAIT lasts 1–4 minutes.

Two reasons for TIME_WAIT (Stevens, Section 2.7):


1. To implement TCP's full-duplex connection termination reliably:
The final ACK may be lost; TIME_WAIT allows retransmission of ACK if server retransmits FIN.
2. To allow old duplicate segments to expire in the network:
Prevents wandering duplicates from a previous connection being accepted as part of a new connection.

Lost duplicate: A TCP segment that gets stuck in a routing loop; arrives late at destination.
TIME_WAIT ensures such segments expire before a new connection reuses the same address/port pair.

Q14. Port Numbers in TCP (10 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO1
Reference: Chapter 2, Sections 2.9–2.10 (Stevens UNP Vol.1)
Answer:
Port numbers (Stevens, Section 2.9) uniquely identify processes within a host for TCP/UDP communication.

Port ranges:
Well-known ports: 0–1023 (assigned by IANA; require root privilege e.g., HTTP=80, FTP=21).
Registered ports: 1024–49151 (registered with IANA for specific services).
Ephemeral (dynamic) ports: 49152–65535 (auto-assigned by OS to clients).

TCP Port Numbers and Concurrent Servers (Section 2.10):


A server binds to a well-known port (e.g., 9877 in Stevens examples).
When a client connects, the OS assigns an ephemeral port to the client.

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 8
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

A TCP connection is uniquely identified by the 4-tuple: {srcIP, srcPort, dstIP, dstPort}.
This allows multiple clients to connect to the same server port simultaneously.

Stevens example: SERV_PORT=9877 is used throughout UNP to avoid conflict with well-known and reserved
ports.

Q15. Relevance of OSI Model in Modern Networking (10 Marks)


Bloom's Level: L4 – Analyze
Course Outcome: CO1
Reference: Chapter 1, Section 1.7 (Stevens UNP Vol.1)
Answer:
The OSI model's continued relevance can be critically evaluated as follows (Stevens, Section 1.7):

Strengths (why it remains relevant):


Provides a universal reference framework for understanding and discussing networking.
Helps in troubleshooting – problems can be isolated to specific layers.
Used in network certification (CCNA, CompTIA Network+) and academic teaching.
Vendor-neutral language for networking concepts.

Limitations (why TCP/IP replaced it in practice):


The OSI model was never fully implemented – TCP/IP dominated the Internet.
Session and Presentation layers have no direct TCP/IP equivalents.
Stevens maps sockets API to layers 5–7 together, showing OSI's practical collapse at upper layers.

Modern relevance:
OSI is used as a conceptual tool, not an implementation blueprint.
TCP/IP is the actual deployed model; OSI is the reference model.
Even Stevens acknowledges: 'We consider the bottom two layers as the device driver and hardware.' (Sec 1.7)

Conclusion: OSI remains academically and practically relevant as a communication framework, but TCP/IP is the
de facto implementation standard.

MODULE 2 – Question Bank


Based on: Chapter 3 (Sockets Introduction), Chapter 4 (Elementary TCP Sockets), and Chapter 5 (TCP
Client/Server Example)

[Link] Questions M L CO

1 What are socket address structures? Explain the address structures for 10 2 CO2
Internet (IPv4 and IPv6) and UNIX domain families with suitable diagrams.

2 Explain byte ordering functions in network programming. Why is byte 10 2 CO2


ordering important? Illustrate with examples of htons(), htonl(), ntohs(), and
ntohl() functions.

3 Discuss the byte manipulation functions in socket programming. Explain 6 2 CO2


bzero(), bcopy(), bcmp(), memset(), memcpy(), and memcmp() with suitable

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 9
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

[Link] Questions M L CO

examples.

4 Explain the inet_aton, inet_addr, and inet_ntoa functions. How do they differ 10 2 CO2
from inet_pton and inet_ntop? Illustrate with examples.

5 Explain Elementary TCP socket functions: socket(), bind(), listen(), accept(), 10 2 CO2
and connect() with their syntax, parameters, and usage.

6 Explain the connect() blind and listen() functions in TCP sockets with a neat 10 2 CO2
diagram. Illustrate the backlog queue mechanism.

7 What are the functions of getsockname() and getpeername()? Explain with 10 2 CO2
suitable examples when each is used.

8 Explain the fork() and exec() functions used in concurrent TCP servers. 10 3 CO2
Discuss how a concurrent server handles multiple clients simultaneously.

9 Explain the TCP Echo client/server example with code. Illustrate the normal 10 2 CO2
startup, data transfer, and normal termination sequences.

10 What happens when a TCP server process terminates abnormally? Discuss 6 3 CO2
SIGPIPE signal and how the client handles it.

11 Explain Value-Result arguments in socket programming. Illustrate how 6 2 CO2


socket address structures are passed between process and kernel.

12 Compare and contrast the sockaddr_in (IPv4), sockaddr_in6 (IPv6), and 10 3 CO2
sockaddr_storage structures. Explain their significance and use cases.

13 Discuss the handling of SIGCHLD signals in a concurrent TCP server. 10 3 CO2


Explain wait() and waitpid() functions and why they are needed.

14 Explain the close() function in TCP sockets. How does it differ from 6 2 CO2
shutdown()? What happens to the connection when close() is called?

15 Trace the complete sequence of system calls and network events from 10 4 CO2
server startup to client connection using a well-labeled diagram for a TCP
Echo client/server.

MODULE 2 – Detailed Answers

Q1. Socket Address Structures (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 3, Section 3.2 (Stevens UNP Vol.1)
Answer:
Socket address structures hold protocol-specific address information (Stevens, Section 3.2).

IPv4 Socket Address Structure (sockaddr_in, Figure 3.1):


struct sockaddr_in {
uint8_t sin_len; // length of structure (16)
sa_family_t sin_family; // AF_INET
in_port_t sin_port; // 16-bit port number (network byte order)
struct in_addr sin_addr; // 32-bit IPv4 address (network byte order)
char sin_zero[8]; // unused – must be zeroed

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 10
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

IPv6 Socket Address Structure (sockaddr_in6, Figure 3.4):


struct sockaddr_in6 {
sa_family_t sin6_family; // AF_INET6
in_port_t sin6_port; // 16-bit port number
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr; // 128-bit IPv6 address
uint32_t sin6_scope_id;
}

Unix Domain (sockaddr_un): uses AF_LOCAL, contains pathname (variable-length).


Generic (sockaddr_storage): large enough to hold any socket address type.

Stevens: 'From an application programmer's point of view, the only use of these generic socket address structures
is to cast pointers to protocol-specific structures.' (Section 3.2)

Q2. Byte Ordering Functions (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 3, Section 3.4 (Stevens UNP Vol.1)
Answer:
Byte ordering is critical because different CPUs store multi-byte integers differently (Stevens, Section 3.4):

Big-Endian: Most significant byte at lowest address (network byte order).


Little-Endian: Least significant byte at lowest address (e.g., Intel x86).

Network byte order is always big-endian. Host byte order depends on CPU.

Four conversion functions (host ↔ network):


htons(x) – host to network short (16-bit): used for port numbers.
htonl(x) – host to network long (32-bit): used for IP addresses.
ntohs(x) – network to host short (16-bit).
ntohl(x) – network to host long (32-bit).

Example (Stevens, Section 3.4):


servaddr.sin_port = htons(13); // convert port 13 to network byte order
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); // wildcard address

On big-endian systems, these are no-ops. On little-endian, they swap bytes.


Rule: Always convert before storing in socket address structures.

Q3. Byte Manipulation Functions (6 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 11
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Reference: Chapter 3, Section 3.5 (Stevens UNP Vol.1)


Answer:
Byte manipulation functions operate on arbitrary byte strings (Stevens, Section 3.5):

Berkeley-derived (b-functions):
bzero(void *dest, size_t nbytes) – zeros nbytes at dest.
bcopy(const void *src, void *dst, size_t nbytes) – copies nbytes from src to dst.
bcmp(const void *ptr1, const void *ptr2, size_t nbytes) – compares two byte strings; returns 0 if equal.

ANSI C functions (POSIX prefers these):


memset(void *dest, int c, size_t len) – fills len bytes with value c.
memcpy(void *dest, const void *src, size_t len) – copies len bytes.
memcmp(const void *ptr1, const void *ptr2, size_t len) – compares byte strings.

Usage in socket programming:


bzero(&servaddr, sizeof(servaddr)); // clear address structure before use
Stevens uses bzero() throughout UNP for clearing socket address structures.

Note: bzero/bcopy/bcmp are from BSD; memset/memcpy/memcmp are ANSI standard (Stevens, Section 3.5).

Q4. inet_aton / inet_ntoa vs inet_pton / inet_ntop (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 3, Sections 3.6–3.7 (Stevens UNP Vol.1)
Answer:
Address conversion functions convert between human-readable IP strings and binary network form (Stevens,
Sections 3.6–3.7):

Older functions (IPv4 only):


inet_aton('[Link]', &addr) – converts dotted-decimal string to 32-bit binary; returns 1 on success.
inet_addr('[Link]') – deprecated version; returns INADDR_NONE (-1) on error (ambiguous for [Link]).
inet_ntoa(addr) – converts 32-bit binary IPv4 to dotted-decimal string (not thread-safe; uses static buffer).

Newer functions (IPv4 and IPv6):


inet_pton(AF_INET, '[Link]', &addr) – presentation to numeric binary.
inet_ntop(AF_INET6, &addr, str, len) – numeric binary to presentation string.
'p' = presentation (human-readable), 'n' = numeric (binary).

Stevens: 'The two functions inet_pton and inet_ntop are new functions that support both IPv4 and IPv6.' (Section
3.7)

Key difference: inet_aton/ntoa are IPv4-only and not thread-safe; inet_pton/ntop are protocol-independent and re-
entrant.
Example: inet_pton(AF_INET, '[Link]', &servaddr.sin_addr);

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 12
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Q5. Elementary TCP Socket Functions (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 4, Sections 4.2–4.6 (Stevens UNP Vol.1)
Answer:
Key TCP socket functions (Stevens, Chapter 4):

1. socket(domain, type, protocol) → sockfd (Section 4.2):


Creates endpoint for communication. Example: socket(AF_INET, SOCK_STREAM, 0)
domain: AF_INET (IPv4), AF_INET6 (IPv6) | type: SOCK_STREAM (TCP), SOCK_DGRAM (UDP)

2. connect(sockfd, &servaddr, addrlen) (Section 4.3):


Client-side: Initiates TCP 3-way handshake. Triggers SYN segment.
Fails if server not listening or connection refused.

3. bind(sockfd, &myaddr, addrlen) (Section 4.4):


Assigns local address (IP + port) to socket. Servers bind to well-known port.
Wildcard address (INADDR_ANY) binds to all local interfaces.

4. listen(sockfd, backlog) (Section 4.5):


Converts socket to passive socket. backlog = max pending connections in queue.
Stevens: Two queues – incomplete connection queue (SYN received) and completed connection queue
(ESTABLISHED).

5. accept(sockfd, &cliaddr, &addrlen) → connfd (Section 4.6):


Blocks until a client connection completes. Returns new connected socket (connfd).
Original sockfd remains listening socket; connfd is used for data exchange.

Q6. connect() and listen() with Backlog Queue (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 4, Sections 4.3 and 4.5 (Stevens UNP Vol.1)
Answer:
connect() (Stevens, Section 4.3):
Called by client to initiate a TCP connection (3-way handshake).
Syntax: int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
The kernel sends a SYN to the server. Returns 0 on success, -1 on error.
Error cases: ETIMEDOUT (no SYN-ACK), ECONNREFUSED (server not listening), EHOSTUNREACH (routing
failure).

listen() (Stevens, Section 4.5):


Called by server to mark socket as passive (accepting connections).
Syntax: int listen(int sockfd, int backlog);
backlog: maximum length of pending connection queue.

Two-queue mechanism (Stevens, Section 4.5, Figure 4.7):

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 13
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Incomplete connection queue: Entries for which SYN received but 3-way handshake not complete. State:
SYN_RCVD.
Completed connection queue: Connections fully established (ESTABLISHED state).
When accept() is called, the kernel removes top entry from completed queue.

Stevens: 'Do not specify a backlog of 0, as different implementations interpret this differently.' (Section 4.5)

Q7. getsockname() and getpeername() (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 4, Section 4.10 (Stevens UNP Vol.1)
Answer:
These functions return the local and remote address of a connected socket (Stevens, Section 4.10):

getsockname(sockfd, &localaddr, &addrlen):


Returns the locally bound address of the socket.
Use cases:
1. After bind() with wildcard IP to find which interface was assigned.
2. After connect() to find the ephemeral port assigned by the kernel.
3. After accept() in server to get local address of the connection.

getpeername(sockfd, &peeraddr, &addrlen):


Returns the address of the remote peer (client) connected to the socket.
Use cases:
1. After accept() – identify which client connected.
2. After exec() – child process uses getpeername to identify its client (because exec doesn't pass args).

Stevens: 'These two functions are required when either the local protocol address of a socket or the foreign
protocol address of a socket is needed.' (Section 4.10)

Example: Server after accept() calls getpeername(connfd, &cliaddr, &len) to log client's IP and port.

Q8. fork() and exec() in Concurrent Servers (10 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO2
Reference: Chapter 4, Sections 4.7–4.8 (Stevens UNP Vol.1)
Answer:
fork() and exec() are fundamental for concurrent server design (Stevens, Sections 4.7–4.8):

fork() (Section 4.7):


Creates a copy of the calling process (child). Returns 0 in child, child PID in parent.
In concurrent server: parent calls accept(), then forks a child to handle each client.
Parent closes connfd; child closes listenfd – each process only needs its relevant socket.

exec() (Section 4.7):

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 14
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Replaces current process image with a new program.


Variants: execl, execv, execle, execve, execlp, execvp.
Used when server wants to exec a separate program to handle a client.

Concurrent server model (Stevens, Section 4.8, Figure 4.12):


for(;;) {
connfd = accept(listenfd, ...); // wait for client
if (fork() == 0) { // child
close(listenfd);
handle_client(connfd);
exit(0);
}
close(connfd); // parent
}

Stevens: Each client is handled in a child process, allowing the server to handle multiple clients simultaneously.

Q9. TCP Echo Client/Server Example (10 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 5, Sections 5.1–5.7 (Stevens UNP Vol.1)
Answer:
TCP Echo Server/Client (Stevens, Chapter 5):

Echo Protocol (Section 5.1):


Client reads line from stdin → sends to server → server echoes back → client prints on stdout.

Server (Figure 5.2) sequence:


socket() → bind() → listen() → accept() → fork() → str_echo() in child
str_echo(): reads from socket, writes back (Figure 5.3).

Client (Figure 5.4) sequence:


socket() → connect() → str_cli() → close()
str_cli(): fgets() from stdin → writen() to server → readline() from server → fputs() to stdout.

Normal startup (Section 5.6):


Server in LISTEN state; client connects → both enter ESTABLISHED.

Normal termination (Section 5.7):


User types EOF (Ctrl+D) → client closes → sends FIN → server str_echo returns → child exits.
Four-way termination: FIN/ACK/FIN/ACK sequence.

Stevens: 'All the basic steps required to implement any client/server are illustrated by this example.' (Section 5.1)

Q10. SIGPIPE and Server Process Termination (6 Marks)

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 15
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Bloom's Level: L3 – Apply


Course Outcome: CO2
Reference: Chapter 5, Sections 5.12 and 5.13 (Stevens UNP Vol.1)
Answer:
When the server process terminates (Stevens, Section 5.12):
Server crash/termination sends FIN to client.
Client receives FIN (read returns 0 – EOF), but if client tries to write again, server sends RST.
A second write after RST generates SIGPIPE signal.

SIGPIPE signal (Section 5.13):


Generated when a process writes to a socket that has received an RST.
Default action: terminate the process.
To handle gracefully: catch SIGPIPE with signal handler or set SIG_IGN, then check errno == EPIPE on write.

Stevens: 'If the process writes to a socket that has received a RST, the SIGPIPE signal is sent to the process.'
(Section 5.13)

Best practice: Always handle SIGPIPE in production servers to avoid unexpected termination.
Example: signal(SIGPIPE, SIG_IGN); // ignore SIGPIPE and handle EPIPE in write() error check

Q11. Value-Result Arguments in Socket Programming (6 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 3, Section 3.3 (Stevens UNP Vol.1)
Answer:
Value-Result arguments refer to how socket address length is passed (Stevens, Section 3.3):

Process to Kernel (value argument):


Functions: bind(), connect(), sendto()
Pass pointer to address structure AND integer size (value).
Example: connect(sockfd, (SA*)&servaddr, sizeof(servaddr));
Kernel knows exactly how many bytes to copy from process.

Kernel to Process (result argument):


Functions: accept(), recvfrom(), getsockname(), getpeername()
Pass pointer to address structure AND pointer to size (result).
Kernel sets the length on return to indicate actual size written.
Example: accept(listenfd, (SA*)&cliaddr, &len); // len is a pointer

Stevens: 'When a socket address structure is passed to any socket function, it is always passed by reference.'
(Section 3.3)

Importance: On 64-bit systems, using socklen_t (not int) for the length argument is critical for correct behavior.

Q12. Comparison of Socket Address Structures (10 Marks)

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 16
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Bloom's Level: L3 – Apply


Course Outcome: CO2
Reference: Chapter 3, Section 3.2 (Stevens UNP Vol.1, Figure 3.6)
Answer:
Stevens (Section 3.2, Figure 3.6) compares five socket address structures:

sockaddr_in (IPv4): Fixed-length, 16 bytes. Fields: sin_len, AF_INET, 16-bit port, 32-bit IPv4 address.
sockaddr_in6 (IPv6): Fixed-length, 28 bytes. Fields: AF_INET6, 16-bit port, 32-bit flow label, 128-bit IPv6 addr, 32-
bit scope ID.
sockaddr_un (Unix domain): Variable-length. Contains AF_LOCAL and pathname (up to 104 bytes).
sockaddr_dl (Datalink): Variable-length. Contains interface index, type, name, and link-layer address.
sockaddr_storage: Variable-length. Opaque fields. Large enough for ANY socket address type. Strictly aligned.

Key points:
IPv4 and IPv6 are fixed-length; Unix domain and datalink are variable-length.
sockaddr_storage introduced with IPv6 to replace the inadequate generic sockaddr.
Stevens: sockaddr_in6 is 64-bit aligned to optimize 128-bit address access on 64-bit processors.

Use case: Use sockaddr_storage when writing protocol-independent code that must handle both IPv4 and IPv6.

Q13. Handling SIGCHLD and wait()/waitpid() (10 Marks)


Bloom's Level: L3 – Apply
Course Outcome: CO2
Reference: Chapter 5, Sections 5.9–5.10 (Stevens UNP Vol.1)
Answer:
In a concurrent server, child processes can become zombies if not properly reaped (Stevens, Section 5.9):

Zombie process: A terminated child process that has not been waited for by its parent.
Takes up process table slot; must be avoided in long-running servers.

Handling SIGCHLD (Section 5.9):


When a child terminates, the kernel sends SIGCHLD to the parent.
Install a signal handler: signal(SIGCHLD, sig_chld);
In handler: call wait() or waitpid() to reap zombie.

wait() vs waitpid() (Section 5.10):


wait() – blocks until ANY child terminates; problematic if multiple children terminate simultaneously.
waitpid(pid, &stat, WNOHANG) – non-blocking; can wait for specific child; preferred in servers.

Stevens (Section 5.10): Using wait() in a loop when multiple SIGCHLDs arrive simultaneously can leave zombies.
Solution: Use waitpid(-1, &stat, WNOHANG) in a loop until it returns ≤ 0.

Example handler:
while (waitpid(-1, NULL, WNOHANG) > 0) ; // reap all terminated children

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 17
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

Q14. close() vs shutdown() in TCP (6 Marks)


Bloom's Level: L2 – Understand
Course Outcome: CO2
Reference: Chapter 4, Section 4.9 & Chapter 6, Section 6.6 (Stevens UNP Vol.1)
Answer:
close() (Stevens, Section 4.9):
Decrements the socket's reference count.
Only sends FIN (initiates 4-way termination) when reference count reaches 0.
In concurrent server: parent calls close(connfd) after fork() – child still has reference, so FIN not sent yet.
Closes both halves (read and write) of the full-duplex connection.

shutdown() (Stevens, Section 6.6):


Immediately initiates the close sequence regardless of reference count.
SHUT_RD: Closes read half (no more receives).
SHUT_WR: Closes write half (sends FIN; still can receive).
SHUT_RDWR: Closes both (same as close but ignores ref count).

Key difference:
close() is reference-count based; shutdown() is immediate.
shutdown(SHUT_WR) is used to send EOF to server while still receiving data (half-close).

Stevens: 'Calling close() on a socket only decrements the descriptor's reference count by 1.' (Section 4.9)

Q15. Complete TCP Echo System Call Trace (10 Marks)


Bloom's Level: L4 – Analyze
Course Outcome: CO2
Reference: Chapter 4 and Chapter 5 (Stevens UNP Vol.1, Figure 4.1 and 5.5)
Answer:
Complete trace of TCP Echo client/server (Stevens, Figures 4.1 and 2.5):

SERVER SIDE:
1. socket(AF_INET, SOCK_STREAM, 0) → listenfd created
2. bind(listenfd, &servaddr, sizeof(servaddr)) → port 9877 bound
3. listen(listenfd, LISTENQ) → socket marked passive
4. accept(listenfd, &cliaddr, &clilen) → BLOCKS waiting for client

CLIENT SIDE (simultaneously):


1. socket(AF_INET, SOCK_STREAM, 0) → sockfd created
2. connect(sockfd, &servaddr, sizeof(servaddr)) → 3-way handshake begins
Network: [client SYN] → [server SYN+ACK] → [client ACK]
3. connect() returns → client is ESTABLISHED

SERVER CONTINUES:
5. accept() returns connfd (new socket for this client)
6. fork() → child handles client, parent loops back to accept()

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 18
Network Programming (MSCS203) | [Link] 2nd Semester | Question Bank

7. Child: str_echo(connfd) – read() then write() in loop

DATA TRANSFER:
Client write() → server read() → server write() → client read()

TERMINATION:
Client close() → sends FIN → server read() returns 0 → child exits
Server close(connfd) → sends FIN → client receives EOF
Server enters TIME_WAIT (2MSL) before fully closing.

Stevens: 'Figure 2.5 shows the actual packet exchange that takes place for a complete TCP connection.' (Section
2.6)

Based on: UNIX Network Programming Vol.1, W. Richard Stevens, 3rd Edition | Page 19

You might also like