CAT 1 QUESTIONS
Define the term network programming.
Write an application class that uses the getLocalHost) method to display the local host
address
i. What is the range of ports allowed for a user defined client/server application?
ii. Briefly explain how a client and server communicates to one another in context of
ports and sockets.
What does the term protocol mean?
Why is a protocol important in a network application?
Distinguish between the protocols UDP and TCP.
i. What is the responsibility of the InetAddress class?
il. In which Java package is the InetAddress class found?
1. Define Network Programming
Network programming is the process of writing programs that allow devices (computers) to
communicate with each other over a network using protocols such as TCP or UDP.
2. Java Application using getLocalHost()
import [Link];
public class LocalHostExample {
public static void main(String[] args) {
try {
InetAddress localHost = [Link]();
[Link]("Host Name: " + [Link]());
[Link]("IP Address: " + [Link]());
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
1
3. Port Range for User-defined Applications
• The range is: 1024 to 65535
• Ports below 1024 are reserved for well-known services.
4. Client-Server Communication (Ports & Sockets)
• A socket is an endpoint for communication.
• A server:
o Opens a socket and binds it to a specific port.
o Listens for incoming client requests.
• A client:
o Connects to the server using the server’s IP address and port number.
• Communication:
o Data is sent and received through sockets using input/output streams.
o Ports ensure data reaches the correct application.
5. What is a Protocol?
A protocol is a set of rules that define how data is transmitted and received over a network.
6. Why Protocols are Important
Protocols ensure:
• Proper formatting of data
• Error detection and correction
• Reliable communication
• Compatibility between different systems
7. Difference Between UDP and TCP
2
Feature TCP (Transmission Control Protocol) UDP (User Datagram Protocol)
Connection Connection-oriented Connectionless
Reliability Reliable (error checking) Unreliable
Speed Slower Faster
Data Order Maintains order No order guarantee
Usage Web, Email Streaming, Gaming
8. Responsibility of InetAddress Class
• It represents an IP address.
• It is used to:
o Get host name and IP address
o Resolve domain names
o Identify local and remote hosts
9. Java Package of InetAddress
• The class belongs to:
[Link] package
CAT 2 QUESTIONS
1)Give the primitive that can be performed by connection-oriented server socket only
2)Which of the primitive are implemented implicitly in TCP sockets
3)Are the send and receive general socket primitive explicitly implemented in tcpsocket? If
not explain how the two general socket primitive are implemented
4)Which steps are different when we implement the server and client tcp sockets
5)Implement a main method in an application class that will:
create a serversocket object with port number (3256)
3
Put the server into a waiting state
Display the message "server in wait state!"
1) Primitive that can be performed only by a connection-oriented server socket
The primitive unique to a connection-oriented server socket is:
accept
• Only a connection-oriented server socket (like TCP’s ServerSocket) can perform the
accept primitive.
• It waits for a connection request from a client and establishes a dedicated connection.
2) Primitives that are implemented implicitly in TCP sockets
TCP sockets automatically implement several connection-oriented primitives behind the scenes:
Implicit TCP primitives
• connect → When a client creates a Socket with a host and port, TCP automatically
performs the connect handshake.
• listen → When a server creates a ServerSocket, TCP implicitly puts it into a listening
state.
• establish → The 3-way handshake (SYN, SYN-ACK, ACK) is done automatically by TCP.
• close → TCP handles connection termination (FIN/ACK exchange) implicitly when you
call close().
3) Are the send and receive general socket primitives explicitly implemented in TCP sockets?
No — they are NOT implemented explicitly.
TCP does not expose raw send and receive primitives directly.
How they are implemented instead
TCP sockets use streams:
• Sending is done through:
o OutputStream → [Link]().write(...)
• Receiving is done through:
4
o InputStream → [Link]().read(...)
So TCP hides the low-level send/receive primitives and replaces them with stream-based I/O.
4) Steps that differ between implementing a TCP server and a TCP client
Server-side steps
1. Create a ServerSocket(port)
2. Call accept() to wait for a client
3. Obtain input/output streams from the returned Socket
4. Communicate
5. Close the connection and server socket
Client-side steps
1. Create a Socket(host, port) → automatically performs connect
2. Obtain input/output streams
3. Communicate
4. Close the socket
Key differences
• Server uses ServerSocket; client uses Socket
• Server must wait using accept()
• Client initiates the connection using new Socket(host, port)
5) Java main method to:
• Create a ServerSocket on port 3256
• Put server in waiting state
• Display "server in wait state!"
✔ Correct Java Implementation
5
CHAPTER 1 — NETWORK PROGRAMMING OVERVIEW
1.1 Definition of Network Programming
Network programming refers to writing programs that communicate over a computer
network. It involves creating software that can send, receive, and process data between
devices.
Key idea: Network programming = programming + communication between machines.
1.2 Core Concepts of Network Programming
• Communication — exchange of data between two or more devices.
• Protocols — rules that govern communication (e.g., TCP, UDP, HTTP).
• Addressing — identifying devices using IP addresses.
• Ports — identifying specific applications/services on a device.
• Sockets — endpoints that enable communication between programs.
• Client–Server Model — one side requests, the other responds.
1.3 Technologies and Languages Used
• Java (most common for teaching network programming)
• Python (simple socket libraries)
• C/C++ (low-level control)
• Go (modern concurrency)
• JavaScript ([Link]) (web-based networking)
6
Java is preferred because:
• Built-in networking libraries
• Platform-independent
• Strong support for multithreading
• Secure and robust
1.4 Applications of Network Programming
• Web servers and browsers
• Email systems
• Chat applications
• File transfer systems
• Distributed systems
• Cloud services
• IoT communication
• Online games
1.5 Introduction to Object-Oriented Programming (OOP) in Java
OOP helps structure network programs into modular, reusable components.
Key OOP Concepts:
• Class — blueprint for objects
• Object — instance of a class
• Encapsulation — hiding internal details
• Inheritance — reusing code
• Polymorphism — one interface, many implementations
• Abstraction — focusing on essential features
Why OOP matters in network programming:
• Makes client/server programs modular
• Easy to extend (e.g., adding new features)
7
• Supports multithreading (important for servers)
1.6 Chapter Summary
• Network programming enables communication between devices.
• Core concepts include protocols, addressing, ports, sockets, and client–server
architecture.
• Java is widely used due to its built-in networking API.
• OOP principles help structure network applications cleanly and professionally.
CHAPTER 2 — PROTOCOLS AND TECHNOLOGY
2.1 Client–Server Model
A communication model where:
• Client → initiates request
• Server → waits and responds
Examples: Web browser (client) → Web server Email client → Mail server
2.2 Ports and Sockets
• Port: A logical communication endpoint (0–65535).
o Well-known ports: HTTP(80), HTTPS(443), FTP(21), SMTP(25)
• Socket: Combination of IP Address + Port Number It represents an endpoint for
communication.
Types of sockets:
• Stream sockets (TCP)
• Datagram sockets (UDP)
2.3 Internet and IP Addresses
IP address uniquely identifies a device on a network.
Types:
• IPv4: 32-bit, e.g., [Link]
• IPv6: 128-bit, e.g., 2001:db8::1
8
Classes of IPv4: A, B, C (public networks) D (multicast) E (experimental)
2.4 Internet Services, URLs, and DNS
• URL (Uniform Resource Locator): Identifies resources on the internet. Example:
[Link]
• DNS (Domain Name System): Converts domain names → IP addresses.
2.5 TCP and UDP
Feature TCP UDP
Type Connection-oriented Connectionless
Reliability Reliable Unreliable
Speed Slower Faster
Use cases Web, email, file transfer Streaming, gaming, VoIP
2.6 Java Networking API Introduction
Java provides built-in classes for networking:
• InetAddress — IP address handling
• Socket — TCP client
• ServerSocket — TCP server
• DatagramSocket — UDP communication
• URL and URLConnection — web communication
2.7 The InetAddress Class
Used to represent IP addresses and hostnames.
Common methods:
• getLocalHost()
• getByName(String host)
• getHostName()
• getHostAddress()
2.8 Chapter Summary
9
• Client–server model is the foundation of network communication.
• Ports and sockets enable communication between applications.
• IP addressing identifies devices.
• DNS resolves names to IPs.
• TCP is reliable; UDP is fast.
• Java provides powerful networking APIs including InetAddress, Socket, and ServerSocket.
CHAPTER 3 — InetAddress CLASS
3.1 What is InetAddress?
InetAddress is a Java class used to represent:
• IP addresses
• Hostnames
• Domain name resolution
It is part of the package: [Link]
3.2 Key Methods and Their Application
Method Description
getLocalHost() Returns local machine IP and hostname
getByName(String host) Resolves hostname to IP
getAllByName(String host) Returns all IPs for a domain
getHostName() Returns hostname
getHostAddress() Returns IP address
isReachable(int timeout) Checks if host is reachable
3.3 Example: Display Local Host Information
10
3.4 Example: Resolve a Domain Name
3.5 Simple Network Application Using InetAddress
Ping-like program:
3.6 Chapter Summary
• InetAddress handles IP addresses and hostnames.
• It provides methods for DNS lookup, local host info, and reachability tests.
• It is the foundation for higher-level networking classes like Socket and ServerSocket.
CHAPTER 4 — SOCKETS
4.1 Definition of a Socket
11
A socket is an endpoint for communication between two machines. It combines:
IP Address + Port Number = Socket
Sockets allow programs to send and receive data over a network.
Types of Sockets
1. Stream Sockets (TCP)
o Connection-oriented
o Reliable
o Uses Socket and ServerSocket in Java
2. Datagram Sockets (UDP)
o Connectionless
o Fast but unreliable
o Uses DatagramSocket and DatagramPacket
4.2 Socket-Based Network Communication
Communication steps:
Client Side
1. Create a socket
2. Connect to server
3. Send request
4. Receive response
5. Close connection
Server Side
1. Create a server socket
2. Bind to a port
3. Wait for client
4. Accept connection
5. Communicate
12
6. Close connection
4.3 TCP Server-Side Programming
Key Java Classes
• ServerSocket — listens for incoming connections
• Socket — represents the connection with a client
• InputStream / OutputStream — data communication
Basic TCP Server Example
Exam Points
• TCP server uses ServerSocket
• Must call accept() to wait for clients
• Communication uses streams
• TCP is reliable and connection-oriented
4.4 Chapter Summary
• Sockets enable communication between applications.
• Two types: TCP (stream) and UDP (datagram).
• TCP server uses ServerSocket to accept connections.
• Communication uses input/output streams.
CHAPTER 5 — TCP SOCKETS
13
5.1 TCP Client-Side Programming
Key Java Classes
• Socket — connects to server
• InputStream / OutputStream — communication
Basic TCP Client Example
5.2 Client–Server Communication Flow
Server
• Creates ServerSocket
• Waits for connection
• Accepts client
• Reads and writes data
Client
• Creates Socket
• Connects to server
• Sends request
• Receives response
5.3 Important TCP Concepts
• Connection-oriented: handshake before communication
• Reliable: guarantees delivery
• Ordered: packets arrive in correct sequence
14
• Stream-based: continuous flow of bytes
5.4 How to Answer Exam Questions
If asked: “Explain TCP communication in Java”
Write:
• TCP uses Socket (client) and ServerSocket (server)
• Server waits using accept()
• Client connects using new Socket(host, port)
• Data is exchanged using streams
• TCP ensures reliability and order
5.5 Chapter Summary
• TCP client uses Socket
• TCP server uses ServerSocket
• Communication uses streams
• TCP is reliable and connection-oriented
CHAPTER 7 — UDP SOCKETS
7.1 UDP Server-Side Programming
Key Java Classes
• DatagramSocket
• DatagramPacket
UDP Server Example
15
7.2 UDP Client-Side Programming
7.3 UDP Communication Characteristics
• Connectionless — no handshake
• Fast — minimal overhead
• Unreliable — no guarantee of delivery
• Packet-based — uses datagrams
7.4 Client–Server Communication Flow (UDP)
Server
• Creates DatagramSocket(port)
• Receives packets
• Processes data
Client
• Creates DatagramSocket()
• Sends packets using send()
7.5 Exam Points
16
• UDP uses DatagramSocket and DatagramPacket
• No connection establishment
• Suitable for real-time applications (VoIP, gaming)
• Faster but unreliable
7.6 Chapter Summary
• UDP is fast and connectionless.
• Uses datagrams instead of streams.
• Server and client use DatagramSocket.
• Communication is packet-based and unreliable.
CHAPTER 8 — MULTI-THREADING CONCEPTS
8.1 Multi-Programming and Multi-Tasking
Multi-Programming
• Running multiple programs on a single CPU.
• CPU switches between programs to maximize utilization.
• Example: Running a browser, music player, and editor at the same time.
Multi-Tasking
• Ability of an OS to execute multiple tasks concurrently.
• Two types:
o Process-based multitasking — multiple programs
o Thread-based multitasking — multiple tasks inside one program
8.2 Processes
A process is:
• An executing program
• Has its own memory space
17
• Heavyweight (expensive to create)
• Communication between processes is complex
Examples:
• [Link]
• [Link]
• [Link]
8.3 Threads
A thread is:
• A lightweight unit of execution inside a process
• Shares memory with other threads
• Faster to create and manage
• Ideal for network servers
Example:
• A chat server where each client runs in its own thread
8.4 Multi-Threading
Multi-threading is the ability of a program to run multiple threads concurrently.
Benefits
• Better CPU utilization
• Faster execution
• Responsive applications
• Essential for network servers (handling many clients)
Use Cases
• Web servers
• Chat applications
• File download managers
• Real-time systems
18
8.5 Chapter Summary
• Multi-programming = multiple programs
• Multi-tasking = multiple tasks
• Process = independent program
• Thread = lightweight execution unit
• Multi-threading improves performance and responsiveness
CHAPTER 9 — MULTI-THREADING IN JAVA
Java provides two main ways to create threads:
9.1 Extending the Thread Class
Steps
1. Create a class that extends Thread
2. Override the run() method
3. Create an object of the class
4. Call start()
Example
Advantages
• Simple to use
Disadvantages
• Cannot extend another class (Java does not support multiple inheritance)
9.2 Implementing the Runnable Interface
19
Steps
1. Create a class that implements Runnable
2. Override run()
3. Create a Thread object and pass the Runnable object
4. Call start()
Example
Advantages
• More flexible
• Allows extending another class
• Preferred in real applications
9.3 Thread Methods
• start() — begins execution
• run() — contains thread logic
• sleep(ms) — pauses thread
• join() — waits for another thread
• isAlive() — checks if running
9.4 Chapter Summary
• Two ways to create threads: extend Thread or implement Runnable
• Runnable is preferred
• Threads improve performance and responsiveness
20
CHAPTER 11 — MULTI-THREADED SERVERS
11.1 Multi-Threaded Server Applications
A multi-threaded server:
• Accepts multiple clients
• Creates a new thread for each client
• Allows simultaneous communication
Why Needed?
• Single-threaded server handles only one client at a time
• Multi-threaded server handles many clients concurrently
11.2 Multi-Threaded TCP Server Example
Server
java
import [Link].*;
import [Link].*;
class ClientHandler extends Thread {
Socket client;
ClientHandler(Socket socket) {
[Link] = socket;
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
String msg = [Link]();
[Link]("Server received: " + msg);
21
[Link]();
} catch (Exception e) {
[Link]();
public class MultiThreadedServer {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(5000);
[Link]("Server running...");
while (true) {
Socket client = [Link]();
new ClientHandler(client).start();
11.3 Unicast, Multicast, and Broadcast Communication
Unicast
• One sender → One receiver
• Example: TCP communication
• Most common in client-server systems
Multicast
• One sender → Selected group of receivers
• Uses special IP range: [Link] – [Link]
• Used in video conferencing, IPTV
Broadcast
• One sender → All devices in a network
22
• Only works in local networks
• Example: DHCP discovery
11.4 Differences Table
Type Sender → Receiver Use Case
Unicast One → One TCP, chat apps
Multicast One → Many (group) IPTV, conferencing
Broadcast One → All DHCP, ARP
11.5 Chapter Summary
• Multi-threaded servers handle multiple clients using threads
• Each client runs in its own thread
• Communication types: unicast, multicast, broadcast
• Multicast uses special IP ranges
• Broadcast is limited to local networks
CHAPTER 12 — COMMUNICATION-BASED SERVICES
12.1 Electronic Mail Services (Email Services)
Electronic mail (email) is one of the earliest and most widely used network communication
services. It allows users to send, receive, store, and forward messages across networks.
Key Components of Email Systems
• User Agent (UA) Applications like Outlook, Gmail, Thunderbird Used to compose, read,
and manage emails
• Mail Transfer Agent (MTA) Responsible for transferring emails between servers
Example: Sendmail, Postfix
• Mail Delivery Agent (MDA) Delivers emails to the recipient’s mailbox
Email Protocols
23
Protocol Purpose
SMTP Sending emails
POP3 Downloading emails (simple)
IMAP Managing emails on server (advanced)
SMTP (Simple Mail Transfer Protocol)
• Used for sending emails
• Works over TCP port 25
• Text-based protocol
• Commands include: HELO, MAIL FROM, RCPT TO, DATA, QUIT
12.2 Socket-Based SMTP Application
Java can be used to implement a simple SMTP client using sockets.
How SMTP Works (Simplified)
1. Client connects to mail server on port 25
2. Server sends greeting
3. Client identifies itself (HELO)
4. Client specifies sender (MAIL FROM)
5. Client specifies recipient (RCPT TO)
6. Client sends message (DATA)
7. Client ends session (QUIT)
12.3 Example: Simple SMTP Client in Java
import [Link].*;
import [Link].*;
public class SimpleSMTPClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("[Link]", 25);
24
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
[Link]([Link]());
[Link]("HELO localhost");
[Link]([Link]());
[Link]("MAIL FROM:<sender@[Link]>");
[Link]([Link]());
[Link]("RCPT TO:<receiver@[Link]>");
[Link]([Link]());
[Link]("DATA");
[Link]([Link]());
[Link]("Subject: Test Email");
[Link]("This is a test email.");
[Link](".");
[Link]([Link]());
[Link]("QUIT");
[Link]();
Exam Points
• SMTP uses TCP port 25
• Commands are text-based
25
• Java uses sockets to communicate with SMTP servers
• Email services rely on UA, MTA, and MDA
12.4 Chapter Summary
• Email services rely on SMTP, POP3, and IMAP
• SMTP is used for sending emails
• Java can implement SMTP using sockets
• Email architecture includes UA, MTA, and MDA
CHAPTER 13 — REMOTE METHOD INVOCATION (RMI)
13.1 What is RMI?
RMI (Remote Method Invocation) allows a Java program to invoke methods on an object
located on another machine.
It enables:
• Distributed computing
• Object-to-object communication over a network
• Pure Java remote communication
13.2 Basic RMI Process
RMI Architecture Components
1. Client Calls remote methods
2. Server Hosts remote objects
3. Remote Interface Defines methods that can be called remotely
4. Stub Client-side proxy for remote object
5. Skeleton Server-side proxy (handled automatically in modern Java)
6. RMI Registry Directory service where remote objects are registered
13.3 Steps in RMI Communication
1. Define a remote interface
26
2. Implement the interface on the server
3. Create server program to register object
4. Create client program to look up object
5. Start RMI registry
6. Run server
7. Run client
13.4 Implementation Details
Step 1: Remote Interface
Step 2: Server Implementation
Step 3: Server Program
Step 4: Client Program
27
13.5 Compilation and Execution
Step 1: Compile all files
javac *.java
Step 2: Start RMI Registry
rmiregistry
Step 3: Run Server
java RMIServer
Step 4: Run Client
java RMIClient
13.6 Exam Points
• RMI enables remote object invocation
• Requires remote interface, server, client, registry
• Uses stubs and skeletons
• Pure Java distributed communication
13.7 Chapter Summary
• RMI is used for distributed Java applications
• Remote interface defines remote methods
• Server registers remote objects
• Client looks up and invokes remote methods
• RMI registry acts as a naming service
28
Umma UNIVERSITY EXAMINATION 2022/2023
YEAR III SEMESTER II EXAMINATION FOR BACHELOR OF
COMPUTER SCIENCE
CSC 420: NETWORK AND DISTRIBUTED PROGRAMMING
DATE: AUGUST 2023 TIME: 2 HOURS
QUESTION ONE [30 MARKS]
(a) Explain the importance of studying Network and Distributed Programming as a unit.
(3 marks)
(b)Differentiate the following terms:
(i) IPv4 vs IPv6 protocols
(ii) Sock_Stream vs Sock_Dgram sockets
(4 marks)
(c) (i)Define a Remote Procedure Call (RPC). (2 marks)
29
(ii) Describe THREE differences between an RPC and a Remote Method Invocation
(RMI) .(6 marks)
(c)(i)Explain the concept of transparency giving an example. (3 marks)
(ii)Explain the task performed by the following client function call:
Import [Link].*;
public class MultiplicationClient {
private InetAddress host;
private int port;
public MultiplicationClient( InetAddress host, int port ) {
[Link] = host;
[Link] = port; }
public void run() { //method used to start the client
try { Socket client = new Socket( host, port );
BufferedReader socketIn;
socketIn = new BufferedReader( new InputStreamReader( [Link]() ) );
PrintWriter socketOut = new PrintWriter(
[Link](), true );
String numbers = "3.4 5.6 7.8";
[Link]( "Multiplying the numbers “ + numbers );
[Link]( numbers );
[Link]( [Link]() );
(8 marks)
(d) Differentiate the following terms:
30
(i) fat vs thin client
(ii) stateful vs stateless server (4 marks)
(a) Importance of studying Network and Distributed Programming (3 marks)
• Enables communication between systems: It allows computers to exchange data over
networks (e.g., client-server applications, web apps).
• Supports distributed systems: Helps in building systems where processing is shared
across multiple machines (e.g., cloud computing).
• Improves scalability and performance: Applications can handle more users and data
efficiently by distributing workload across multiple nodes.
(b) Differences
(i) IPv4 vs IPv6 protocols (2 marks)
Feature IPv4 IPv6
Address size 32-bit 128-bit
Format Decimal (e.g., [Link]) Hexadecimal (e.g., 2001:db8::1)
Address space Limited Very large
Security Optional Built-in (IPSec)
(ii) SOCK_STREAM vs SOCK_DGRAM sockets (2 marks)
Feature SOCK_STREAM SOCK_DGRAM
Protocol TCP UDP
Connection Connection-oriented Connectionless
Reliability Reliable Unreliable
Data flow Continuous stream Independent packets
31
(c)
(i) Remote Procedure Call (RPC) definition (2 marks)
A Remote Procedure Call (RPC) is a communication mechanism that allows a program to
execute a procedure on a remote machine as if it were a local function call.
(ii) THREE differences: RPC vs RMI (6 marks)
Feature RPC RMI
Language support Language-independent Java-specific
Data handling Uses simple data types Supports objects
Programming model Procedural Object-oriented
(c) (second part)
(i) Transparency concept (3 marks)
Transparency in distributed systems means hiding the complexity of the system from users so
that it appears as a single system.
Example:
Accessing a file on a remote server as if it is stored locally on your computer.
(ii) Explanation of the client function (8 marks)
This Java client program performs the following tasks:
• Creates a socket connection:
Connects to a server using the provided host and port.
• Sets up input and output streams:
o BufferedReader → receives data from the server
o PrintWriter → sends data to the server
• Prepares data:
A string "3.4 5.6 7.8" representing numbers to multiply
32
• Sends request to server:
The numbers are sent to the server using [Link](numbers);
• Receives response:
The client waits and reads the result from the server using [Link]()
• Displays output:
Prints the multiplication result returned by the server
Summary:
The client sends numbers to a server, the server multiplies them, and returns the result which is
displayed on the client side.
(d) Differences
(i) Fat client vs Thin client (2 marks)
Feature Fat Client Thin Client
Processing Done on client Done on server
Resource usage High Low
Dependency Less on server Highly dependent on server
(ii) Stateful vs Stateless server (2 marks)
Feature Stateful Server Stateless Server
Memory Stores client state Does not store state
Requests Dependent on previous requests Independent requests
Complexity More complex Simpler
QUESTION TWO [20 MARKS]
(a)(i) Define the term association as used in network and distributed programming.
33
(2 marks)
(ii) Illustrate the declaration and explain the five parameters that constitute such an association.
(10 marks)
(b Explain the various parts of the following network code snippet:
import [Link].*;
import [Link].*;
public void run() {
try {
ServerSocket ss = new ServerSocket( port );
Socket incoming = [Link]();
BufferedReader in;
in = new BufferedReader( new InputStreamReader(
[Link]() ) );
PrintWriter out = new PrintWriter(
[Link](), true );
String str;
while ( !(str = [Link]()).equals("") ) {
double result = 0;
StringTokenizer st = new StringTokenizer( str );
try {
while( [Link]() ) {
Double d = new Double( [Link]() );
result += [Link]();
[Link]( "The result is " + result );
34
}
catch( NumberFormatException nfe ) {
[Link]( "Sorry, your list contains "
+ "an invalid number" );
[Link]();
(8 marks)
(a)
(i) Definition of Association (2 marks)
An association in network and distributed programming refers to a communication link
established between two processes, defined by a combination of IP addresses and port
numbers at both ends.
In simple terms:
It identifies who is communicating with whom over a network.
(ii) Declaration and explanation of five parameters (10 marks)
Illustration (Example Association)
An association can be represented as:
(Local IP, Local Port, Remote IP, Remote Port, Protocol)
Explanation of the five parameters
1. Local IP Address
o Identifies the client or server machine initiating communication
o Example: [Link]
2. Local Port Number
35
o Identifies the specific application/process on the local machine
o Example: 5000
3. Remote IP Address
o Identifies the destination machine in the network
o Example: [Link]
4. Remote Port Number
o Identifies the application/service on the remote machine
o Example: 8080
5. Protocol (TCP/UDP)
o Defines the communication rules used
o Example: TCP (reliable) or UDP (fast but unreliable)
Summary:
These five parameters together uniquely define a communication session between two
endpoints.
(b) Explanation of the Network Code Snippet (8 marks)
This Java code represents a server program that receives numbers from a client, processes
them, and returns the result.
Breakdown of the code
1. Import statements
import [Link].*;
import [Link].*;
• [Link].* → Handles input/output streams
• [Link].* → Provides networking classes (e.g., sockets)
36
2. Creating a server socket
ServerSocket ss = new ServerSocket(port);
• Creates a server that listens on a specified port
• Waits for client connections
3. Accepting a client connection
Socket incoming = [Link]();
• Accepts a connection request from a client
• Returns a socket for communication
4. Setting up input and output streams
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter(
[Link](), true);
• BufferedReader → Reads data sent by the client
• PrintWriter → Sends data back to the client
5. Reading client input
while (!(str = [Link]()).equals(""))
• Continuously reads lines from the client
• Stops when an empty string is received
6. Processing the data
StringTokenizer st = new StringTokenizer(str);
• Splits the input string into individual numbers
37
while([Link]()) {
Double d = new Double([Link]());
result += [Link]();
}
• Converts each token into a number
• Adds them to compute the total sum
7. Sending result to client
[Link]("The result is " + result);
• Sends the computed sum back to the client
8. Error handling
catch(NumberFormatException nfe)
• Handles invalid input (non-numeric values)
• Sends an error message to the client
9. Closing connection
[Link]();
• Terminates the connection after processing
QUESTION THREE [20 MARKS]
(a) Network and distributed programming revolves around various types of network models.
With the use of suitable diagrams, describe any THREE of those models. (6 marks)
(b) (i) State your understanding of a generic Application Programming Interface (API).
(1 mark)
(ii) Explain the various parts of the following socket declaration:
int socket(int domain, int type, int protocol)
38
(3 marks)
(iii) Write relevant program snippets to illustrate the functions used for sending and receiving
data in network programs. (10 marks)
(a) THREE network models (6 marks)
1. Client–Server Model
• A central server provides services/resources to multiple clients.
• Clients send requests; the server processes and responds.
• Example: Web browsing (browser → web server).
2. Peer-to-Peer (P2P) Model
• All nodes act as both clients and servers.
• No central authority; each peer shares resources.
• Example: File sharing systems.
39
3. Distributed System Model
• Multiple independent computers work together as one system.
• Tasks are divided among nodes for efficiency.
• Example: Cloud computing systems.
(b)
(i) Generic API (1 mark)
An Application Programming Interface (API) is a set of rules and functions that allows different
software applications to communicate and interact with each other.
(ii) Socket declaration explanation (3 marks)
int socket(int domain, int type, int protocol);
• domain
o Specifies the communication domain (address family)
o Example: AF_INET (IPv4), AF_INET6 (IPv6)
• type
o Defines the communication type
o Example: SOCK_STREAM (TCP), SOCK_DGRAM (UDP)
• protocol
o Specifies the protocol to use
o Usually set to 0 (system selects default for given type)
(iii) Program snippets for sending and receiving data (10 marks)
40
1. Using TCP (SOCK_STREAM)
Sending data (Client side)
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
char msg[] = "Hello Server";
send(sockfd, msg, strlen(msg), 0);
Receiving data (Server side)
int new_sock;
char buffer[1024];
new_sock = accept(sockfd, (struct sockaddr*)&client_addr, &addr_len);
recv(new_sock, buffer, sizeof(buffer), 0);
printf("Message: %s\n", buffer);
2. Using UDP (SOCK_DGRAM)
Sending data
sendto(sockfd, msg, strlen(msg), 0,
(struct sockaddr*)&server_addr, sizeof(server_addr));
Receiving data
recvfrom(sockfd, buffer, sizeof(buffer), 0,
(struct sockaddr*)&client_addr, &addr_len);
QUESTION FOUR [20 MARKS]
(a) (i) List THREE examples of protocol domains used in network and distributed
41
programming. (3
marks)
(ii) Outline THREE advantages, and TWO disadvantages of a connection-oriented protocol in
network programming. (5 marks)
(b) (i) State what you understand by a system call. (2 marks)
(ii) Write appropriate network program snippets to implement the following functions:
1. listen()
2. accept()
(10 marks)
(a)
(i) THREE examples of protocol domains (3 marks)
• AF_INET – IPv4 Internet protocols
• AF_INET6 – IPv6 Internet protocols
• AF_UNIX (AF_LOCAL) – Local inter-process communication (same machine)
(ii) Advantages and disadvantages of connection-oriented protocol (TCP) (5 marks)
Advantages
• Reliable communication: Guarantees delivery of data (no loss).
• Ordered data transfer: Packets arrive in the correct sequence.
• Error checking and recovery: Detects and retransmits lost/corrupted data.
Disadvantages
• Slower performance: Due to connection setup and acknowledgments.
• Higher overhead: Uses more resources (memory, bandwidth).
(b)
(i) System call (2 marks)
42
A system call is a mechanism through which a program requests a service from the operating
system kernel, such as file handling or network communication.
(ii) Program snippets (10 marks)
1. listen() function
Used by a server to wait for incoming connection requests
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
listen(sockfd, 5); // 5 = maximum number of queued connections
Explanation:
• Converts the socket into a passive socket
• Prepares it to accept incoming connections
• The parameter 5 is the backlog (queue size)
2. accept() function
Used to accept a client connection
int new_sock;
struct sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
new_sock = accept(sockfd, (struct sockaddr*)&client_addr, &addr_len);
Explanation:
• Accepts a pending connection from the queue
• Returns a new socket descriptor for communication
• The original socket (sockfd) continues listening
43
QUESTION FIVE [20 MARKS]
(a) (i) Explain the function performed by the following program segment:
int bind(listenFD, &serverAddrCast, sizeof(serverAddr));
int listen(listenFD, 5);
(4 marks)
(ii) With the use of appropriate diagrams, compare and contrast OSI 7-layer reference model
with the TCP/IP suites. (6 marks)
(b) Write a suitable network program to implement the connect() function. (10 marks)
(a)
(i) Function of the program segment (4 marks)
int bind(listenFD, &serverAddrCast, sizeof(serverAddr));
int listen(listenFD, 5);
• bind()
o Associates the socket (listenFD) with a specific IP address and port number
(serverAddrCast).
o This allows the server to be identified on the network.
• listen()
o Converts the socket into a passive (listening) socket.
o Enables the server to accept incoming connection requests.
o The value 5 specifies the maximum number of queued connections (backlog).
Summary:
These two functions prepare a server socket to receive and queue incoming client connections.
(ii) OSI vs TCP/IP models (6 marks)
44
4
Comparison
Feature OSI Model TCP/IP Model
Layers 7 layers 4 layers
Nature Conceptual (reference model) Practical (used in Internet)
Layers breakdown More detailed Simpler and compact
Usage Teaching & design Real-world networking
Mapping between models
OSI Layers TCP/IP Equivalent
Application, Presentation, Session Application
Transport Transport
Network Internet
Data Link + Physical Network Access
45
Key Point:
OSI is a theoretical model, while TCP/IP is the actual implementation used on the Internet.
(b) Network program implementing connect() (10 marks)
Below is a simple TCP client program in C demonstrating the use of connect():
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int sockfd;
struct sockaddr_in server_addr;
char *message = "Hello Server";
char buffer[1024];
// Create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// Configure server address
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
server_addr.sin_addr.s_addr = inet_addr("[Link]");
// Connect to server
connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
// Send message
send(sockfd, message, strlen(message), 0);
// Receive response
recv(sockfd, buffer, sizeof(buffer), 0);
printf("Server reply: %s\n", buffer);
// Close socket
close(sockfd);
46
return 0;
}
Explanation of connect()
• Establishes a connection between client and server
• Requires:
o Socket descriptor (sockfd)
o Server address (server_addr)
• Used only in connection-oriented protocols (TCP)
47