0% found this document useful (0 votes)
4 views

network programming

The document contains a series of programming assignments focused on networking and socket programming in Java, including the implementation of echo applications, client-server models, and remote method invocation (RMI) for various mathematical operations. It provides detailed code examples for each task, covering server and client implementations, as well as explanations of networking concepts such as connection-oriented and connectionless networking. Additionally, it discusses design considerations for client-server applications and the strengths and weaknesses of Java as a network programming language.

Uploaded by

ABDUL HALEEM
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

network programming

The document contains a series of programming assignments focused on networking and socket programming in Java, including the implementation of echo applications, client-server models, and remote method invocation (RMI) for various mathematical operations. It provides detailed code examples for each task, covering server and client implementations, as well as explanations of networking concepts such as connection-oriented and connectionless networking. Additionally, it discusses design considerations for client-server applications and the strengths and weaknesses of Java as a network programming language.

Uploaded by

ABDUL HALEEM
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

Assignment

Networking and Socket Programming Questions and Answers

1. Write a program for Java Echo Application using socket programming.

Answer:

A Java Echo Application allows a client to send a message to the server, and the server echoes it back. Below is
the Java program:

Server (EchoServer.java)

import java.io.*;
import java.net.*;

public class EchoServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
System.out.println("Server is listening on port 5000...");

while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected!");

BufferedReader input = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);

String message;
while ((message = input.readLine()) != null) {
System.out.println("Received: " + message);
output.println("Echo: " + message);
}

socket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Client (EchoClient.java)

import java.io.*;
import java.net.*;

public class EchoClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {

System.out.println("Connected to server. Type a message: ");


String message;
while ((message = userInput.readLine()) != null) {
output.println(message);
System.out.println("Server response: " + input.readLine());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

2. Write a client-side program to read information from the server using socket.

Answer:

The following Java program connects to a server and reads a response:

import java.io.*;
import java.net.*;

public class ClientReader {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 6000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {

String serverResponse;
while ((serverResponse = input.readLine()) != null) {
System.out.println("Server says: " + serverResponse);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

3. Write a program to perform basic text messaging between client and server.

Answer:

This Java program enables a simple chat between a client and a server.

Server (ChatServer.java)

import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(7000);
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in))) {

System.out.println("Client connected. Start chatting...");


String clientMessage, serverMessage;
while ((clientMessage = input.readLine()) != null) {
System.out.println("Client: " + clientMessage);
System.out.print("Server: ");
serverMessage = userInput.readLine();
output.println(serverMessage);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Client (ChatClient.java)

import java.io.*;
import java.net.*;

public class ChatClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 7000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in))) {

System.out.println("Connected to server. Start chatting...");

String clientMessage, serverMessage;


while (true) {
System.out.print("Client: ");
clientMessage = userInput.readLine();
output.println(clientMessage);

serverMessage = input.readLine();
System.out.println("Server: " + serverMessage);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

4. Define client-server model. Explain design considerations for client-server applications.

Answer:

The Client-Server Model is a network architecture where a server provides services, and clients request those
services.

Design Considerations:

1. Concurrency: The server should handle multiple client requests simultaneously.


2. Security: Implement authentication and encryption.
3. Scalability: The system should handle an increasing number of clients.
4. Reliability: The application should manage network failures effectively.
5. Performance: Optimize resource usage for faster response times.

5. Explain connection-oriented networking and connectionless networking.

Answer:

1. Connection-Oriented Networking:
o Requires an established connection before data transfer (e.g., TCP).
o Reliable and ensures data integrity.
o Used in applications like email, web browsing, and file transfers.
2. Connectionless Networking:
o No dedicated connection is required (e.g., UDP).
o Faster but less reliable.
o Used in applications like VoIP and online gaming.

6. Explain about Network Programming Features and Scope.

Answer:

Features of Network Programming:

 Communication between computers using sockets.


 Support for multiple protocols (TCP/IP, UDP).
 Concurrent connections handling.
 Data transmission and security management.

Scope:

 Used in web development, cloud computing, IoT, and cybersecurity.

7. What is the client-server software model? Explain the strengths and weaknesses of Java as a network
programming language.

Answer:

Client-Server Software Model:


A distributed architecture where a server provides services, and multiple clients request these services.

Strengths of Java for Network Programming:

 Platform Independence: Runs on any OS.


 Robust Libraries: Java provides powerful networking APIs.
 Security Features: Supports encryption and authentication.
 Multithreading: Allows handling multiple client requests.

Weaknesses:
 Performance Overhead: JVM adds some latency.
 Memory Consumption: Requires more memory than C or C++.

8. Explain different Network Programming Tools and Platforms available in the market.

Answer:

1. Wireshark: A network protocol analyzer.


2. Putty: A SSH and Telnet client.
3. Netcat: A simple TCP/IP debugging tool.
4. NSLookup & Ping: Used for DNS and connectivity testing.
5. Java Networking API: Provides socket programming capabilities.
6. Node.js: Used for server-side networking applications.
7. Python’s Socket Library: Simplifies network programming.

Assignment 2 (Chapter:2)

1. Write a program that prints the address of www.tufohss.edu.np.


2. Write a program that finds the address of the local machine. [hint:- get
local host].
3. Write a program that finds the canonical host name of a given address
i.e 182.93.84.136
4. Write a program that find IP address and Hostname of the local machine.
5. Write a program to get IPV4 and IPV6 address of a given web address.
6. Write a program for determining whether an IP address is IPV4 or IPV6.
7. Write a program for testing character of an IP address.
8. Write a program that lists all the network interfaces.
9. Write a program that use of network interfaces getter methods.
10. Write a program to check remote system is reachable or not. [Testing
Reachability]
UNIT 3 Questions
1. Write a program that splits the part of URL [splitting URL into
pieces of information]
2. Write a program that check in which protocols does a virtual
mechine support or not?
3. Write a program to download a web pages of a given web address
4. Write a program for resolving relative URI.
5. Write a program to demonstrate the x-www-form-url encoded
string [2024].
6. Explain about x-www-form URI encoded and URI Decoder with
Example. [2024]

Assingment- 3:
Q.1)WAP to add two numbers using RMI.

Q.2)WAP to subtract two numbers using RMI.

Q.3) WAP to find factorial numbers using RMI.

Q.4)WAP to multiply two numbers using RMI.

Q.5)write a program to calculate area of triangle using RMI.

Write short notes on:- i) RMI Server ii) RMI

Q.6) What is RMI? Write a RMI Client and server program to find greater number among two numbers.
[advance java 2024]

Here is the complete solution with each question followed by its corresponding answer.

Q.1) WAP to add two numbers using RMI.

Answer:

To add two numbers using Java RMI, we need three main components:
1. Remote Interface (Addition.java)
2. Server Implementation (AdditionServer.java)
3. Client Implementation (AdditionClient.java)

1. Remote Interface (Addition.java)

import java.rmi.*;

public interface Addition extends Remote {


int add(int a, int b) throws RemoteException;
}

2. Server Implementation (AdditionServer.java)

import java.rmi.*;
import java.rmi.server.*;

public class AdditionServer extends UnicastRemoteObject implements Addition {


public AdditionServer() throws RemoteException {
super();
}

public int add(int a, int b) throws RemoteException {


return a + b;
}

public static void main(String args[]) {


try {
AdditionServer obj = new AdditionServer();
Naming.rebind("rmi://localhost/AddService", obj);
System.out.println("Addition Server is Ready.");
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}

3. Client Implementation (AdditionClient.java)

import java.rmi.*;

public class AdditionClient {


public static void main(String args[]) {
try {
Addition obj = (Addition) Naming.lookup("rmi://localhost/AddService");
System.out.println("Sum: " + obj.add(10, 20));
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}

Q.2) WAP to subtract two numbers using RMI.

Answer:

1. Remote Interface (Subtraction.java)


import java.rmi.*;

public interface Subtraction extends Remote {


int subtract(int a, int b) throws RemoteException;
}

2. Server Implementation (SubtractionServer.java)

import java.rmi.*;
import java.rmi.server.*;

public class SubtractionServer extends UnicastRemoteObject implements Subtraction {


public SubtractionServer() throws RemoteException {
super();
}

public int subtract(int a, int b) throws RemoteException {


return a - b;
}

public static void main(String args[]) {


try {
SubtractionServer obj = new SubtractionServer();
Naming.rebind("rmi://localhost/SubtractService", obj);
System.out.println("Subtraction Server is Ready.");
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}

3. Client Implementation (SubtractionClient.java)

import java.rmi.*;

public class SubtractionClient {


public static void main(String args[]) {
try {
Subtraction obj = (Subtraction)
Naming.lookup("rmi://localhost/SubtractService");
System.out.println("Difference: " + obj.subtract(50, 20));
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}

Q.3) WAP to find factorial using RMI.

Answer:

1. Remote Interface (Factorial.java)

import java.rmi.*;

public interface Factorial extends Remote {


int factorial(int n) throws RemoteException;
}
2. Server Implementation (FactorialServer.java)

import java.rmi.*;
import java.rmi.server.*;

public class FactorialServer extends UnicastRemoteObject implements Factorial {


public FactorialServer() throws RemoteException {
super();
}

public int factorial(int n) throws RemoteException {


if (n == 0) return 1;
return n * factorial(n - 1);
}

public static void main(String args[]) {


try {
FactorialServer obj = new FactorialServer();
Naming.rebind("rmi://localhost/FactorialService", obj);
System.out.println("Factorial Server is Ready.");
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}

3. Client Implementation (FactorialClient.java)

import java.rmi.*;

public class FactorialClient {


public static void main(String args[]) {
try {
Factorial obj = (Factorial) Naming.lookup("rmi://localhost/FactorialService");
System.out.println("Factorial of 5: " + obj.factorial(5));
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}

Q.4) WAP to multiply two numbers using RMI.

Answer:

(Same structure as addition, replace add with multiply.)

1. Remote Interface (Multiplication.java)

import java.rmi.*;

public interface Multiplication extends Remote {


int multiply(int a, int b) throws RemoteException;
}

2. Server Implementation (MultiplicationServer.java)

import java.rmi.*;
import java.rmi.server.*;

public class MultiplicationServer extends UnicastRemoteObject implements Multiplication {


public MultiplicationServer() throws RemoteException {
super();
}

public int multiply(int a, int b) throws RemoteException {


return a * b;
}

public static void main(String args[]) {


try {
MultiplicationServer obj = new MultiplicationServer();
Naming.rebind("rmi://localhost/MultiplyService", obj);
System.out.println("Multiplication Server is Ready.");
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}

3. Client Implementation (MultiplicationClient.java)

import java.rmi.*;

public class MultiplicationClient {


public static void main(String args[]) {
try {
Multiplication obj = (Multiplication)
Naming.lookup("rmi://localhost/MultiplyService");
System.out.println("Product: " + obj.multiply(5, 6));
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}

Q.5) Write a program to calculate the area of a triangle using RMI.

Answer:

1. Remote Interface (TriangleArea.java)

import java.rmi.*;

public interface TriangleArea extends Remote {


double area(double base, double height) throws RemoteException;
}

2. Server Implementation (TriangleAreaServer.java)

import java.rmi.*;
import java.rmi.server.*;

public class TriangleAreaServer extends UnicastRemoteObject implements TriangleArea {


public TriangleAreaServer() throws RemoteException {
super();
}
public double area(double base, double height) throws RemoteException {
return 0.5 * base * height;
}

public static void main(String args[]) {


try {
TriangleAreaServer obj = new TriangleAreaServer();
Naming.rebind("rmi://localhost/TriangleAreaService", obj);
System.out.println("Triangle Area Server is Ready.");
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}

3. Client Implementation (TriangleAreaClient.java)

import java.rmi.*;

public class TriangleAreaClient {


public static void main(String args[]) {
try {
TriangleArea obj = (TriangleArea)
Naming.lookup("rmi://localhost/TriangleAreaService");
System.out.println("Triangle Area: " + obj.area(5, 10));
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}

Here are the remaining answers for the questions.

Q.6) What is RMI? Write an RMI Client and Server program to find the greater number
among two numbers.

Answer:

Remote Method Invocation (RMI)

RMI (Remote Method Invocation) is a mechanism in Java that allows an object to invoke methods on an
object running on another machine or JVM. It provides a way for Java programs to communicate over a
network by calling remote methods as if they were local methods.

1. Remote Interface (Greater.java)

import java.rmi.*;

public interface Greater extends Remote {


int findGreater(int a, int b) throws RemoteException;
}

2. Server Implementation (GreaterServer.java)


import java.rmi.*;
import java.rmi.server.*;

public class GreaterServer extends UnicastRemoteObject implements Greater {


public GreaterServer() throws RemoteException {
super();
}

public int findGreater(int a, int b) throws RemoteException {


return (a > b) ? a : b;
}

public static void main(String args[]) {


try {
GreaterServer obj = new GreaterServer();
Naming.rebind("rmi://localhost/GreaterService", obj);
System.out.println("Greater Number Server is Ready.");
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}

3. Client Implementation (GreaterClient.java)

import java.rmi.*;

public class GreaterClient {


public static void main(String args[]) {
try {
Greater obj = (Greater) Naming.lookup("rmi://localhost/GreaterService");
System.out.println("Greater number is: " + obj.findGreater(25, 18));
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}

Short Notes

i) RMI Server

RMI Server is the component that hosts and provides remote services. It registers remote objects with the RMI
Registry and listens for client requests. The main responsibilities of an RMI server include:

1. Implementing a remote interface.


2. Extending UnicastRemoteObject to create remote objects.
3. Registering the remote object with the Naming.rebind() method.
4. Running the server so that clients can access the remote methods.

Example:

Naming.rebind("rmi://localhost/MyService", obj);

ii) RMI (Remote Method Invocation)


Remote Method Invocation (RMI) is a Java API that enables an object to call methods on an object running in
another JVM, either on the same machine or over a network.

Key Features of RMI:

1. Remote Communication – Allows method calls between different JVMs.


2. Serialization – Converts objects into a format that can be transmitted over a network.
3. Security – Uses SecurityManager to prevent unauthorized access.
4. Dynamic Class Loading – Transfers objects' class definitions dynamically.

This completes all the questions with proper explanations and code. Let me know if you need further
clarifications! 🚀

2019

Detailed Answers – Network Application Questions


2. Define Client-Server Model of Network Application. Explain the Design
Considerations of Network Applications.

Client-Server Model

The Client-Server Model is a networking framework where a client requests services and a server provides
them. The client initiates communication, and the server responds.

Example

 A web browser (client) requests a webpage from a web server.


 The web server processes the request and sends the page to the browser.

Design Considerations for Network Applications

1. Scalability – The system should handle multiple clients simultaneously.


2. Security – Implement encryption (SSL/TLS), authentication, and firewall protection.
3. Reliability – Ensure system recovery in case of failures.
4. Performance – Minimize latency and optimize resource usage.
5. Interoperability – The application should work across different platforms.

3. Write a Program to Show IP and MAC Address of the System and Check if the IP
Address is IPv4 or IPv6.

Java Program to Display IP and MAC Address


import java.net.*;

public class IPandMAC {


public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("IP Address: " + ip.getHostAddress());

NetworkInterface network = NetworkInterface.getByInetAddress(ip);


byte[] mac = network.getHardwareAddress();

System.out.print("MAC Address: ");


for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
System.out.println();

// Check IPv4 or IPv6


if (ip.getHostAddress().contains(":")) {
System.out.println("The IP Address is IPv6");
} else {
System.out.println("The IP Address is IPv4");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Output Example:

IP Address: 192.168.1.10
MAC Address: 00-1A-2B-3C-4D-5E
The IP Address is IPv4

4. Define URL Connection Class. Write a Program to Read Header Using Header-
Specific Methods.

Definition of URLConnection Class

URLConnection is a Java class used to establish a connection with a URL. It allows sending requests, receiving
responses, and reading headers from a web page or API.

Java Program to Read HTTP Headers


import java.net.*;
import java.io.*;

public class URLHeaderReader {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection conn = url.openConnection();

System.out.println("Content Type: " + conn.getContentType());


System.out.println("Content Length: " + conn.getContentLength());
System.out.println("Date: " + conn.getDate());
System.out.println("Last Modified: " + conn.getLastModified());

} catch (Exception e) {
e.printStackTrace();
}
}
}

5. Write the Functions of Socket. Explain the Configuration Options of TCP Client
Socket.

Functions of a Socket

A socket is an endpoint for network communication.

1. bind() – Assigns an address to the socket.


2. listen() – Listens for incoming connections (server-side).
3. accept() – Accepts an incoming connection.
4. connect() – Connects to a remote socket (client-side).
5. send() / receive() – Transfers data.
6. close() – Closes the socket.

TCP Client Socket Configuration Options

 SO_TIMEOUT – Sets a timeout for blocking operations.


 SO_KEEPALIVE – Keeps the connection alive.
 TCP_NODELAY – Disables buffering for immediate sending.

6. Define Secure Socket. Write a Program to Create a Secure Client Socket.

A Secure Socket uses SSL/TLS encryption to protect data transfer. It ensures:

 Confidentiality – Data is encrypted.


 Integrity – Prevents data tampering.
 Authentication – Verifies identities.

Java Program for Secure Client Socket


import javax.net.ssl.*;
import java.io.*;

public class SecureClient {


public static void main(String[] args) {
try {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) factory.createSocket("localhost", 443);

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);


out.println("Hello Secure Server!");

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
System.out.println("Server Response: " + in.readLine());

socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

7. Define Buffer. Explain Buffer Handling Methods.

Definition of Buffer

A buffer is a temporary storage area used to store data before processing. In networking, buffers handle
incoming and outgoing data streams.

Buffer Handling Methods in Java (Using ByteBuffer)

1. allocate(int capacity) – Allocates buffer memory.


2. put(byte[] data) – Stores data into the buffer.
3. flip() – Switches from writing to reading mode.
4. get() – Reads data from the buffer.
5. clear() – Resets the buffer.
8. Write Short Notes on (Any Two)

a) HTTP Methods

HTTP methods define how clients interact with a web server.

 GET – Retrieves data from the server.


 POST – Submits data to be processed.
 PUT – Updates an existing resource.
 DELETE – Deletes a resource.

b) Datagram Packet

A DatagramPacket is used in UDP communication. It represents a data packet sent or received over a network
without establishing a connection.

c) Multicast Socket

A MulticastSocket allows a sender to send packets to multiple receivers simultaneously. It is useful for video
streaming and live broadcasts.

Detailed Answers – Network Application Questions (Part 2)

9(a) Differentiate Between URL and URI Class with Their Applications
Feature URL (Uniform Resource Locator) URI (Uniform Resource Identifier)

Definition A specific address to locate a resource on the web. A general term that includes both URLs and URNs.

mailto:[email protected],
Example https://www.example.com/page.html
urn:isbn:0451450523

Used for web browsing, API requests, and file


Usage Used for identifying resources in a uniform way.
downloads.

Components Protocol (HTTP/HTTPS), domain, and resource path. Can be a URL or URN (Uniform Resource Name).

Java Class java.net.URL java.net.URI

Applications

 URL: Used for accessing web pages, APIs, and downloading resources.
 URI: Used for general resource identification, including email addresses and ISBN numbers.

9(b) Write a Program to Illustrate the Application of RMI

Remote Method Invocation (RMI)


RMI allows Java programs to call methods remotely on other machines.

Steps to Implement RMI

1. Create a remote interface.


2. Implement the interface.
3. Create a server program.
4. Create a client program.

1. Remote Interface (RMIInterface.java)


import java.rmi.*;

public interface RMIInterface extends Remote {


String sayHello(String name) throws RemoteException;
}

2. Remote Object Implementation (RMIServer.java)


import java.rmi.*;
import java.rmi.server.*;

public class RMIServer extends UnicastRemoteObject implements RMIInterface {


protected RMIServer() throws RemoteException {
super();
}

public String sayHello(String name) throws RemoteException {


return "Hello, " + name + "! Welcome to RMI.";
}

public static void main(String args[]) {


try {
RMIInterface obj = new RMIServer();
Naming.rebind("rmi://localhost:5000/hello", obj);
System.out.println("RMI Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}

3. Client Program (RMIClient.java)


import java.rmi.*;

public class RMIClient {


public static void main(String args[]) {
try {
RMIInterface obj = (RMIInterface) Naming.lookup("rmi://localhost:5000/hello");
String response = obj.sayHello("Abdul");
System.out.println("Server Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Run the RMI Registry Before Executing the Server

rmiregistry 5000 &

10. Write a TCP Multithreaded Server and Client Socket Program to Check if a
Number Sent by the Client is Prime or Composite.

1. TCP Multithreaded Server (TCPServer.java)


import java.io.*;
import java.net.*;

class ClientHandler extends Thread {


private Socket clientSocket;

public ClientHandler(Socket socket) {


this.clientSocket = socket;
}

private boolean isPrime(int num) {


if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

public void run() {


try {
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

int number = Integer.parseInt(in.readLine());


String result = (isPrime(number)) ? "Prime" : "Composite";

out.println("The number " + number + " is " + result);


clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

public class TCPServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
System.out.println("Server is listening on port 5000...");
while (true) {
Socket socket = serverSocket.accept();
new ClientHandler(socket).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

2. TCP Client (TCPClient.java)


import java.io.*;
import java.net.*;

public class TCPClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)) {
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

System.out.print("Enter a number: ");


int number = Integer.parseInt(userInput.readLine());

out.println(number);
System.out.println("Server Response: " + in.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ How It Works:

1. The server listens for incoming connections.


2. When a client connects, a new thread is created.
3. The client sends a number, and the server checks if it's prime or composite.
4. The result is sent back to the client.

11. Write a Program to Create UDP Server and Client Which Converts Date from
BS to AD Format.

Assumption:

 BS (Bikram Sambat) is 56 years, 8 months, and 17 days ahead of AD.

1. UDP Server (UDPServer.java)


import java.net.*;
import java.io.*;

public class UDPServer {


public static void main(String[] args) {
try (DatagramSocket serverSocket = new DatagramSocket(5000)) {
byte[] receiveBuffer = new byte[1024];
byte[] sendBuffer;

System.out.println("UDP Server is running...");


while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
serverSocket.receive(receivePacket);

String bsDate = new String(receivePacket.getData(), 0,


receivePacket.getLength());
String adDate = convertBSToAD(bsDate);
sendBuffer = adDate.getBytes();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();

DatagramPacket sendPacket = new DatagramPacket(sendBuffer,


sendBuffer.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static String convertBSToAD(String bsDate) {


String[] parts = bsDate.split("-");
int bsYear = Integer.parseInt(parts[0]);
int bsMonth = Integer.parseInt(parts[1]);
int bsDay = Integer.parseInt(parts[2]);

int adYear = bsYear - 56;


int adMonth = bsMonth - 8;
int adDay = bsDay - 17;

if (adMonth <= 0) {
adMonth += 12;
adYear--;
}
if (adDay <= 0) {
adDay += 30;
adMonth--;
}

return adYear + "-" + adMonth + "-" + adDay;


}
}

2. UDP Client (UDPClient.java)


import java.net.*;
import java.io.*;

public class UDPClient {


public static void main(String[] args) {
try (DatagramSocket clientSocket = new DatagramSocket()) {
InetAddress serverAddress = InetAddress.getByName("localhost");
byte[] sendBuffer;
byte[] receiveBuffer = new byte[1024];

String bsDate = "2080-10-25";


sendBuffer = bsDate.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,


serverAddress, 5000);
clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,


receiveBuffer.length);
clientSocket.receive(receivePacket);

String adDate = new String(receivePacket.getData(), 0,


receivePacket.getLength());
System.out.println("Converted AD Date: " + adDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}

2018

2. Define Client Server software model. Explain the features of Java as a Network programming
language.

Answer:

Client-Server Software Model:

The client-server software model is a distributed application architecture where tasks are divided between
servers, which provide resources or services, and clients, which request those services.

 Server: A server is a program that listens for incoming requests from clients and provides the requested
services. It typically runs on a powerful machine with ample resources.
 Client: A client is a program that initiates requests to the server for specific services. It typically runs on
a user's machine or device.

Features of Java as a Network Programming Language:

 Platform Independence: Java's "write once, run anywhere" capability allows network applications to
run on various operating systems without modification.
 Rich Networking API: Java provides a comprehensive set of classes and interfaces in the java.net
package, making it easy to develop network applications.
 Object-Oriented: Java's object-oriented nature promotes code reusability, modularity, and
maintainability, which are essential for complex network applications.
 Multithreading: Java's built-in multithreading support allows servers to handle multiple client requests
concurrently, improving performance and scalability.
 Security Features: Java includes robust security features, such as code verification and security
managers, which are crucial for protecting network applications from threats.
 Exception Handling: Java's exception handling mechanism allows developers to write robust and fault-
tolerant network applications.

3. What is the use of NetworkInterface Class? Explain the basic features of NetworkInterface class.

Answer:

Use of NetworkInterface Class:

The NetworkInterface class in Java represents a network interface, which can be a physical or virtual network
adapter. It provides methods to access information about network interfaces, such as their names, addresses, and
hardware addresses.
Basic Features of NetworkInterface Class:

 Retrieving Network Interfaces: The NetworkInterface class provides static methods like
getNetworkInterfaces() and getByName() to retrieve network interfaces.
 Accessing Interface Information: It offers methods to get the name (getName()), display name
(getDisplayName()), hardware address (getHardwareAddress()), and MTU (getMTU()) of a network
interface.
 Retrieving IP Addresses: The getInetAddresses() method returns an enumeration of all IP addresses
assigned to the network interface.
 Checking Interface Status: Methods like isUp(), isLoopback(), isVirtual(), and
isPointToPoint() allow you to check the status and type of a network interface.
 Subinterfaces: The getSubInterfaces() method returns an enumeration of subinterfaces associated
with the network interface.

4. Explain HTTP methods with example.

Answer:

HTTP Methods:

HTTP (Hypertext Transfer Protocol) defines a set of methods that indicate the desired action to be performed on
a resource identified by a given URI.

 GET: Retrieves a resource. It is used for read-only operations and should not modify the server state.
o Example: GET /index.html HTTP/1.1
 POST: Submits data to be processed to a specified resource. It is often used for creating or updating
resources.
o Example: Submitting a form with user data.
 PUT: Replaces all current representations of the target resource with the request payload.
o Example: Uploading a file to a specific location on the server.
 DELETE: Deletes the specified resource.
o Example: Deleting a blog post or a user account.
 HEAD: Same as GET, but only retrieves the headers, not the message body.
o Example: Checking the existence of a resource or its last modification time.
 OPTIONS: Describes the communication options for the target resource.
o Example: Determining which HTTP methods are supported by the server.
 TRACE: Performs a message loop-back test along the path to the target resource.
o Example: Debugging proxy or firewall issues.
 CONNECT: Establishes a tunnel to the server identified by the target resource.
o Example: Used for establishing secure connections through proxies.

5. Write a program to display the socket information [address, port, local address, local port].

Answer:

Java
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketInfo {


public static void main(String[] args) {
try {
Socket socket = new Socket("www.example.com", 80); // Connect to a remote
server
InetAddress remoteAddress = socket.getInetAddress();
int remotePort = socket.getPort();
InetAddress localAddress = socket.getLocalAddress();
int localPort = socket.getLocalPort();

System.out.println("Remote Address: " + remoteAddress);


System.out.println("Remote Port: " + remotePort);
System.out.println("Local Address: " + localAddress);
System.out.println("Local Port: " + localPort);

socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

6. Write a server side program for daytime service using socket.

Answer:

Java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class DaytimeServer {

public static void main(String[] args) {


try (ServerSocket serverSocket = new ServerSocket(13)) { // Daytime service uses
port 13
System.out.println("Daytime server started on port 13...");
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(new Date().toString());
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

7. Define Non-blocking I/O. Differentiate between blocking and non-blocking socket communication in
Java.

Answer:

Non-blocking I/O:
Non-blocking I/O is a mode of operation where I/O operations (such as reading from or writing to a socket)
return immediately, even if the operation cannot be completed. The calling thread does not wait for the
operation to finish.

Difference between Blocking and Non-blocking Socket Communication in Java:

 Blocking Sockets:
o When a thread performs a blocking I/O operation (e.g., read() or accept()), it waits until the
operation completes.
o If no data is available or no connection is made, the thread is blocked (suspended) until the I/O
operation can proceed.
o Simpler to use but can lead to performance issues if multiple clients are handled by a single
thread.
 Non-blocking Sockets:
o I/O operations return immediately, even if they cannot be completed.
o The thread can perform other tasks while waiting for I/O operations to complete.
o Requires more complex code to handle the asynchronous nature of I/O.
o Improves performance and scalability by allowing a single thread to manage multiple
connections.
o Java's NIO (New I/O) package provides support for non-blocking I/O using channels and
selectors.

8. Write Short Notes on (Any Two):

a) Secure Communication

Answer:

Secure communication involves protecting data transmitted over a network from unauthorized access,
modification, or disclosure. It relies on cryptographic techniques to ensure confidentiality, integrity, and
authentication.

 Confidentiality: Ensures that only authorized parties can access the data. Achieved through encryption.
 Integrity: Ensures that data is not altered during transmission. Achieved through hashing and digital
signatures.
 Authentication: Verifies the identity of the communicating parties. Achieved through digital
certificates and passwords.
 Protocols: Common secure communication protocols include SSL/TLS, HTTPS, SSH, and VPNs.

b) Multicast Sockets

Answer:

Multicast sockets allow data to be sent to multiple recipients simultaneously. Instead of sending data to a single
destination, multicast sends data to a group of recipients identified by a multicast IP address.

 Group Communication: Multicast is used for applications that require group communication, such as
video conferencing, online gaming, and stock ticker updates.
 Efficiency: Multicast is more efficient than unicast (sending data to each recipient individually) when
sending data to multiple recipients.
 IP Addresses: Multicast uses a special range of IP addresses
9. What is the Procedure of Socket Communication?

Procedure for Creating a Socket Communication

A socket is an endpoint for sending or receiving data across a network. The basic procedure for socket communication is
as follows:

1. Steps for a TCP Server

1. Create a Server Socket: Use ServerSocket to listen for client connections.


2. Accept Client Connection: When a client requests a connection, accept it.
3. Create Input/Output Streams: Use BufferedReader and PrintWriter to exchange data.
4. Process Client Request: Perform necessary operations based on client input.
5. Send Response to Client: Return processed data.
6. Close the Connection: Close the socket.

2. Steps for a TCP Client

1. Create a Client Socket: Use Socket to connect to the server.


2. Create Input/Output Streams: Send and receive data.
3. Send Data to Server: Write data to the output stream.
4. Receive Data from Server: Read data from the input stream.
5. Close the Connection: Close the socket.

Socket Options with Example

A socket has several configuration options that determine its behavior. These options can be modified using the
setOption() method.

Common Socket Options

Option Description

SO_TIMEOUT Sets the timeout for reading data.

SO_KEEPALIVE Keeps the connection active by sending periodic signals.

TCP_NODELAY Disables Nagle’s algorithm to send small packets immediately.

SO_REUSEADDR Allows multiple sockets to bind to the same address.

Example of Setting Socket Options


java
CopyEdit
import java.net.*;

public class SocketOptionsExample {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5000);
// Setting socket options
socket.setSoTimeout(5000); // Timeout for reading data
socket.setKeepAlive(true); // Keep connection alive
socket.setTcpNoDelay(true); // Disable Nagle’s algorithm

System.out.println("Socket options set successfully.");

socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

10. Write a Program to Perform a Basic Two-Way Communication Between Client


and Server.

This program demonstrates a simple two-way communication where the client sends a message and the server
responds.

1. TCP Server (TCPServer.java)


java
CopyEdit
import java.io.*;
import java.net.*;

public class TCPServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
System.out.println("Server is waiting for a connection...");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");

// Creating input and output streams


BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Reading message from client


String message = in.readLine();
System.out.println("Client: " + message);

// Sending response to client


out.println("Hello, Client! Message Received.");

socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

2. TCP Client (TCPClient.java)


java
CopyEdit
import java.io.*;
import java.net.*;

public class TCPClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)) {
// Creating input and output streams
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

// Sending message to server


out.println("Hello, Server!");

// Receiving response from server


String response = in.readLine();
System.out.println("Server: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ How It Works:

1. The server waits for client connections.


2. The client connects and sends a message.
3. The server responds to the client.
4. Both close the connection.

11. Features of DatagramPacket and DatagramSocket Class

1. Features of DatagramPacket Class

 Used to send and receive data in UDP communication.


 Supports data buffering for efficient transmission.
 Provides methods to retrieve sender details (IP, port).

2. Features of DatagramSocket Class

 Provides socket communication for UDP.


 Supports both unicast and broadcast communication.
 Allows setting timeouts and buffer sizes for better performance.

UDP Client-Server Communication Example

1. UDP Server (UDPServer.java)


java
CopyEdit
import java.net.*;

public class UDPServer {


public static void main(String[] args) {
try (DatagramSocket serverSocket = new DatagramSocket(5000)) {
byte[] receiveBuffer = new byte[1024];
byte[] sendBuffer;

System.out.println("UDP Server is running...");

while (true) {
// Receiving data from client
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
serverSocket.receive(receivePacket);
String receivedData = new String(receivePacket.getData(), 0,
receivePacket.getLength());

System.out.println("Received from Client: " + receivedData);

// Processing and sending response


String response = "Message Received: " + receivedData.toUpperCase();
sendBuffer = response.getBytes();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();

DatagramPacket sendPacket = new DatagramPacket(sendBuffer,


sendBuffer.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

2. UDP Client (UDPClient.java)


java
CopyEdit
import java.net.*;

public class UDPClient {


public static void main(String[] args) {
try (DatagramSocket clientSocket = new DatagramSocket()) {
InetAddress serverAddress = InetAddress.getByName("localhost");
byte[] sendBuffer;
byte[] receiveBuffer = new byte[1024];

String message = "Hello UDP Server";


sendBuffer = message.getBytes();

// Sending data to server


DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
serverAddress, 5000);
clientSocket.send(sendPacket);

// Receiving response from server


DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
clientSocket.receive(receivePacket);

String response = new String(receivePacket.getData(), 0,


receivePacket.getLength());
System.out.println("Server Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ How It Works:

1. The UDP server waits for client messages.


2. The client sends a message to the server.
3. The server processes and responds.
4. The client receives the response.

2019

9. What is the procedure for constructing and connecting Server sockets? Explain the Server Socket
options with example.

Answer:

Procedure for Constructing and Connecting Server Sockets:

1. Create a ServerSocket:
o Instantiate a ServerSocket object, specifying the port number on which the server will listen for
incoming connections.
o ServerSocket serverSocket = new ServerSocket(port);
2. Listen for Connections:
o Call the accept() method on the ServerSocket object. This method blocks until a client
attempts to connect.
o Socket clientSocket = serverSocket.accept();
3. Handle Client Connection:
o The accept() method returns a Socket object representing the connection with the client.
o Use the Socket object to communicate with the client (e.g., read input, write output).
4. Close the Sockets:
o After the communication is complete, close the Socket and ServerSocket objects to release
resources.
o clientSocket.close();
o serverSocket.close();

Server Socket Options with Example:

 setSoTimeout(int timeout): Sets the timeout for the accept() method. If no client connection is
established within the specified timeout, a SocketTimeoutException is thrown.
o Example:

Java

ServerSocket serverSocket = new ServerSocket(8080);


serverSocket.setSoTimeout(5000); // 5 seconds timeout
try {
Socket clientSocket = serverSocket.accept();
// ... handle client connection ...
} catch (java.net.SocketTimeoutException e) {
System.err.println("Accept timeout");
}
 bind(SocketAddress bindpoint): Binds the ServerSocket to a specific local address and port. This
is useful when the server has multiple network interfaces.
o Example:

Java

ServerSocket serverSocket = new ServerSocket();


InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
serverSocket.bind(address);

 setReuseAddress(boolean on): Enables or disables the SO_REUSEADDR socket option. This option
allows the server to bind to a port even if it was recently used by another process.
o Example:

Java

ServerSocket serverSocket = new ServerSocket();


serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(8080));

10. Write a program to perform a basic two-way communication between client and server.

Answer:

Server Code (Server.java):

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

public static void main(String[] args) {


try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server started on port 8080...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
out.println("Server received: " + inputLine);
}

clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Code (Client.java):

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {

public static void main(String[] args) {


try (Socket socket = new Socket("127.0.0.1", 8080)) {
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

Scanner scanner = new Scanner(System.in);


String userInput;

while (true) {
System.out.print("Enter message (or 'exit'): ");
userInput = scanner.nextLine();
out.println(userInput);

if (userInput.equalsIgnoreCase("exit")) {
break;
}

String serverResponse = in.readLine();


System.out.println("Server: " + serverResponse);
}

scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

11. What are features of DatagramPacket and Datagramsocket Class? Write a program to create a
simple UDP client.

Answer:

Features of DatagramPacket and DatagramSocket Class:

 DatagramPacket:
o Represents a datagram packet, which is a unit of data that can be sent or received over a network
using UDP.
o Contains the data to be sent or received, the destination or source address, and the destination or
source port.
o Used for connectionless communication, where packets are sent independently and may arrive
out of order or be lost.
 DatagramSocket:
o Represents a socket for sending and receiving datagram packets.
o Used for connectionless communication over UDP.
o Can be used to send and receive datagram packets to and from any destination.

Program to Create a Simple UDP Client:

Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class UDPClient {

public static void main(String[] args) {


try (DatagramSocket socket = new DatagramSocket();
Scanner scanner = new Scanner(System.in)) {

InetAddress address = InetAddress.getByName("127.0.0.1"); // Server address


int port = 9876; // Server port

System.out.print("Enter message: ");


String message = scanner.nextLine();
byte[] buffer = message.getBytes();

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address,


port);
socket.send(packet);

System.out.println("Message sent.");

} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

This client sends a message to a server running on localhost at port 9876. To test this, you would need to create
a UDP server that listens on that port.

Opens in a new window

Alright, let's tackle the Network Programming exam paper from the 2018 batch, question by question.

Subject: Network Programming 2018 Batch

Group B

Attempt any SIX questions

12. What is Client-Server software model? Explain the strengths and weaknesses of Java programming
as a network programming language.
Answer:

Client-Server Software Model:

The client-server software model is a distributed application architecture where tasks are divided between
servers and clients.

 Server: A program that provides services or resources to clients.


 Client: A program that requests services or resources from a server.

Strengths of Java as a Network Programming Language:

 Platform Independence: Java's "write once, run anywhere" capability allows network applications to
run on various operating systems without modification.
 Rich Networking API: Java provides a comprehensive set of classes and interfaces in the java.net
package, making it easy to develop network applications.
 Object-Oriented: Java's object-oriented nature promotes code reusability, modularity, and
maintainability.
 Multithreading: Java's built-in multithreading support allows servers to handle multiple client requests
concurrently.
 Security Features: Java includes robust security features, such as code verification and security
managers.
 Exception Handling: Java's exception handling mechanism allows developers to write robust and fault-
tolerant network applications.

Weaknesses of Java as a Network Programming Language:

 Performance Overhead: Java's virtual machine can introduce some performance overhead compared to
languages like C or C++.
 Verbose Syntax: Java's syntax can be more verbose than some other languages, which can increase
development time.
 Memory Consumption: Java applications can sometimes consume more memory than applications
written in other languages.

13. What is the use of InetAddress class? Write a program to retrieve IP and MAC address?

Answer:

Use of InetAddress Class:

The InetAddress class in Java represents an Internet Protocol (IP) address. It is used to get the IP address of a
host (machine) and to perform operations on IP addresses.

Program to Retrieve IP and MAC Address:

Java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class NetworkInfo {


public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("IP Address: " + localHost.getHostAddress());

NetworkInterface network = NetworkInterface.getByInetAddress(localHost);


byte[] macAddressBytes = network.getHardwareAddress();
if (macAddressBytes != null) {
StringBuilder macAddress = new StringBuilder();
for (int i = 0; i < macAddressBytes.length; i++) {
macAddress.append(String.format("%02X%s", macAddressBytes[i], (i <
macAddressBytes.length - 1) ? "-" : ""));
}
System.out.println("MAC Address: " + macAddress.toString());
} else {
System.out.println("MAC Address: Not available");
}

} catch (UnknownHostException | SocketException e) {


e.printStackTrace();
}
}
}

14. Define URL class. Write a program to show the parts of the URL (Splitting URL).

Answer:

URL Class:

The URL class in Java represents a Uniform Resource Locator (URL), which is a reference to a resource on the
World Wide Web.

Program to Show Parts of the URL:

Java
import java.net.MalformedURLException;
import java.net.URL;

public class URLParts {

public static void main(String[] args) {


try {
URL url = new URL("https://www.example.com:8080/path/to/file?
query=123#fragment");

System.out.println("Protocol: " + url.getProtocol());


System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Path: " + url.getPath());
System.out.println("Query: " + url.getQuery());
System.out.println("Fragment: " + url.getRef());

} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}

15. Define Socket. Differentiate between TCP and UDP Sockets with their applications.
Answer:

Socket:

A socket is an endpoint for communication between two machines over a network. It provides an interface for
sending and receiving data.

TCP Sockets vs. UDP Sockets:

 TCP (Transmission Control Protocol):


o Connection-oriented.
o Reliable, ordered delivery of data.
o Error checking and retransmission.
o Slower than UDP.
o Applications: Web browsing (HTTP), file transfer (FTP), email (SMTP).
 UDP (User Datagram Protocol):
o Connectionless.
o Unreliable, unordered delivery of data.
o No error checking or retransmission.
o Faster than TCP.
o Applications: Video streaming, online gaming, DNS lookups.

16. Define cookies. Write a program to retrieve cookie information stored in the system.

Answer:

Cookies:

Cookies are small pieces of data that a server sends to a client's web browser. The browser may store the
cookies and send them back to the server with later requests. Cookies are used for various purposes, such as
session management, personalization, and tracking.

Program to Retrieve Cookie Information:

Retrieving cookie information directly from the system is generally not possible with Java's standard libraries.
Cookies are typically managed by web browsers. To retrieve cookies, you would need to use a web browser
automation tool or a library that interacts with the browser's cookie storage.

17. Define IP Multicast. Write a program to join a computer system in a multicast group.

Answer:

IP Multicast:

IP multicast is a network communication technique for delivering data to a group of recipients simultaneously.
Instead of sending data to each recipient individually, the sender sends data to a multicast group address.

Program to Join a Multicast Group:

Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastReceiver {

public static void main(String[] args) {


try (MulticastSocket socket = new MulticastSocket(4446)) {
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.joinGroup(group);

byte[] buffer = new byte[256];


DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

System.out.println("Waiting for multicast messages...");


socket.receive(packet);

String message = new String(packet.getData(), 0, packet.getLength());


System.out.println("Received: " + message);

socket.leaveGroup(group);
} catch (IOException e) {
e.printStackTrace();
}
}
}

18. Write Short Notes on (Any Two):

a) HTTP

Answer:

HTTP (Hypertext Transfer Protocol) is an application-layer protocol for distributed, collaborative, hypermedia
information systems. It is the foundation of data communication for the World Wide Web. HTTP is a request-
response protocol in the client-server model.

 Methods: HTTP defines methods like GET, POST, PUT, DELETE, etc., to indicate the desired action.
 Headers: HTTP messages include headers that provide metadata about the request or response.
 Status Codes: HTTP responses include status codes that indicate the outcome of the request.

b) RMI

Answer:

RMI (Remote Method Invocation) is a Java API that allows an object running in one Java virtual machine
(JVM) to invoke methods on an object running in another JVM. RMI enables distributed computing in Java.

 Remote Interfaces: RMI uses remote interfaces to define the methods that can be invoked remotely.
 Stubs and Skeletons: RMI generates stubs and skeletons to handle communication between the client
and server JVMs.
 Registry: RMI uses a registry to locate remote objects.

c) Secure Socket

Answer:
A secure socket is a socket that provides secure communication over a network using encryption and
authentication protocols, such as SSL/TLS. This ensures that data is protected from eavesdropping and
tampering.

 Encryption: Secure sockets encrypt data before transmission to ensure confidentiality.


 Authentication: Secure sockets authenticate the communicating parties to ensure identity.

19. Write multithreaded TCP client and server socket programs for daytime service.

Answer:

Server Code (MultithreadedDaytimeServer.java):

Java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class MultithreadedDaytimeServer {

public static void main(String[] args) {


try (ServerSocket serverSocket = new ServerSocket(13)) {
System.out.println("Daytime server started on port 13...");
while (true) {
Socket clientSocket = serverSocket.accept();
new Thread(new ClientHandler(clientSocket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static class ClientHandler implements Runnable {


private Socket clientSocket;

public ClientHandler(Socket clientSocket) {


this.clientSocket = clientSocket;
}

@Override
public void run() {
try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true))
{
out.println(new Date().toString());
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Client Code (DaytimeClient.java):

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class DaytimeClient {

public static void main(String[] args) {


try (Socket socket = new Socket("127.0.0.1", 13);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {

String daytime = in.readLine();


System.out.println("Daytime: " + daytime);

} catch (IOException e) {
e.printStackTrace();
}
}
}

20. Write UDP client and server socket programs in which the server identifies the number sent by a
client is either even or odd and replies to client accordingly.

Answer:

Server Code (UDPEvenOddServer.java):

Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPEvenOddServer {

public static void main(String[] args) {


try (DatagramSocket socket = new DatagramSocket(9876)) {
byte[] buffer = new byte[256];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

System.out.println("Server started on port 9876...");


while (true) {
socket.receive(packet);
String message = new String(packet.getData(), 0,
packet.getLength()).trim();
int number = Integer.parseInt(message);

String response = (number % 2 == 0) ? "Even" : "Odd";


byte[] responseBuffer = response.getBytes();
DatagramPacket responsePacket = new DatagramPacket(responseBuffer,
responseBuffer.length, packet.getAddress(), packet.getPort());
socket.send(responsePacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client Code (UDPEvenOddClient.java):


Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPEvenOddClient {

public static void main(String[] args) {


try (DatagramSocket socket = new DatagramSocket();
Scanner scanner = new Scanner(System.in)) {

InetAddress address = InetAddress.getByName("127.0.0.1");


int port = 9876;

System.out.print("Enter a number: ");


String message = scanner.nextLine();
byte[] buffer = message.getBytes();

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address,


port);
socket.send(packet);

byte[] responseBuffer = new byte[256];


DatagramPacket responsePacket = new DatagramPacket(responseBuffer,
responseBuffer.length);
socket.receive(responsePacket);

String response = new String(responsePacket.getData(), 0,


responsePacket.getLength()).trim();
System.out.println("Server: " + response);

} catch (IOException e) {
e.printStackTrace();
}
}
}

21. How blocking I/O is differing from Non-Blocking I/O? Explain the basic mechanism of handling
Buffers and Channels in Java with example.

Answer:

Blocking I/O vs. Non-Blocking I/O:

 Blocking I/O:
o When a thread performs a blocking I/O operation (e.g., read() or accept()), it waits until the
operation completes.
o If no data is available or no connection is made, the thread is blocked (suspended) until the I/O
operation can proceed.
o Simpler to use but can lead to performance issues if multiple clients are handled by a single
thread.
 Non-Blocking I/O:
o I/O operations return immediately, even if they cannot be completed.
o The thread can perform other tasks while waiting for I/O operations to complete.
o Requires more complex code to handle the asynchronous nature of I/O.
o Improves performance and scalability by allowing a single thread to manage multiple
connections.
o Java's NIO (New I/O) package provides support for non-blocking I/O using channels and
selectors.

Basic Mechanism of Handling Buffers and Channels in Java with Example:

Java NIO (New I/O) provides channels and buffers for non-blocking I/O.

 Channels:
o Represent connections to I/O devices (e.g., files, sockets).
o Can be used for reading and writing data.
o Support non-blocking operations.
 Buffers:
o Hold data temporarily during I/O operations.
o Provide methods for reading and writing data, as well as for managing their position, limit, and
capacity.

Example:

Java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {

public static void main(String[] args) {


try (SocketChannel channel = SocketChannel.open()) {
channel.connect(new InetSocketAddress("127.0.0.1", 8080));
ByteBuffer buffer = ByteBuffer.wrap("Hello, NIO!".getBytes());
channel.write(buffer);
buffer.clear();
channel.read(buffer);
String response = new String(buffer.array(), 0, buffer.position());
System.out.println("Response: " + response);

} catch (IOException e) {
e.printStackTrace();
}
}
}

RR Campus

1. Write a java program using TCP that enables chatting between client and server.

Answer:

Server Code (ChatServer.java):

Java
import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Chat Server started on port 8080...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

BufferedReader consoleIn = new BufferedReader(new


InputStreamReader(System.in));
String clientMessage, serverMessage;

while (true) {
if ((clientMessage = in.readLine()) != null) {
System.out.println("Client: " + clientMessage);
System.out.print("Server: ");
serverMessage = consoleIn.readLine();
out.println(serverMessage);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client Code (ChatClient.java):

Java
import java.io.*;
import java.net.*;

public class ChatClient {


public static void main(String[] args) {
try (Socket socket = new Socket("127.0.0.1", 8080)) {
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

BufferedReader consoleIn = new BufferedReader(new


InputStreamReader(System.in));
String clientMessage, serverMessage;

while (true) {
System.out.print("Client: ");
clientMessage = consoleIn.readLine();
out.println(clientMessage);

if ((serverMessage = in.readLine()) != null) {


System.out.println("Server: " + serverMessage);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. Describe any 5 InetAddress object methods to find IP address types.

Answer:

 isAnyLocalAddress(): Returns true if the IP address is a wildcard address.


 isLoopbackAddress(): Returns true if the IP address is a loopback address.
 isLinkLocalAddress(): Returns true if the IP address is a link-local address.
 isSiteLocalAddress(): Returns true if the IP address is a site-local address.
 isMulticastAddress(): Returns true if the IP address is a multicast address.

3. What is RMI? Discuss architecture of RMI.

Answer:

RMI (Remote Method Invocation):

RMI is a Java API that allows an object running in one Java virtual machine (JVM) to invoke methods on an
object running in another JVM. It enables distributed computing in Java.

RMI Architecture:

 Remote Interface: Defines the methods that can be invoked remotely.


 Remote Object Implementation: Implements the remote interface.
 Stub: A client-side proxy for the remote object.
 Skeleton: A server-side proxy that dispatches calls to the remote object implementation.
 RMI Registry: A naming service that allows clients to locate remote objects.

4. What is InetAddress class? Explain the IPv4 Socket Address Structure and IPv6 Socket Address
Structure.

Answer:

InetAddress Class:

The InetAddress class represents an Internet Protocol (IP) address. It is used to get the IP address of a host and
to perform operations on IP addresses.

IPv4 Socket Address Structure:

 IP Address (32 bits): Represents the IPv4 address of the host.


 Port Number (16 bits): Represents the port number on which the process is listening.

IPv6 Socket Address Structure:

 IP Address (128 bits): Represents the IPv6 address of the host.


 Port Number (16 bits): Represents the port number on which the process is listening.
 Flow Information (20 bits): Used for traffic flow labeling.
 Scope ID (16 bits): Used to identify the scope of the address.

5. What are the core components consist of Java NIO? Explain any two.
Answer:

Java NIO Core Components:

 Buffers: Hold data temporarily during I/O operations.


 Channels: Represent connections to I/O devices (files, sockets).
 Selectors: Allow a single thread to monitor multiple channels for I/O events.

Explanation of Two Components:

 Buffers: Buffers are used to hold data during I/O operations. They provide methods for reading and
writing data, as well as for managing their position, limit, and capacity.
 Channels: Channels represent connections to I/O devices. They can be used for reading and writing
data, and they support non-blocking operations.

6. What is a Port? Create a simple port scanner program to check the open ports for the specified host
name.

Answer:

Port:

A port is a 16-bit number that identifies a specific process or service running on a host.

Port Scanner Program:

Java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class PortScanner {


public static void main(String[] args) {
String host = "127.0.0.1"; // Replace with the host you want to scan
int startPort = 1;
int endPort = 1024;

for (int port = startPort; port <= endPort; port++) {


try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), 200); // 200 ms timeout
System.out.println("Port " + port + " is open");
} catch (IOException e) {
// Port is closed or filtered
}
}
}
}

7. What is Cookie? Explain about CookieHandler, CookieManager, CookiePolicy, CookieStore and


HttpCookie class.

Answer:

Cookie:
A cookie is a small piece of data that a server sends to a client's web browser. The browser may store the cookie
and send it back to the server with later requests.

 CookieHandler: An abstract class that provides a framework for implementing HTTP cookie
management.
 CookieManager: A concrete implementation of CookieHandler that manages the storage and retrieval
of cookies.
 CookiePolicy: Defines the rules for accepting or rejecting cookies.
 CookieStore: An interface that represents a storage for cookies.
 HttpCookie: A class that represents an HTTP cookie.

Group - C

Long Questions (Any One) 1x10=10

a) List all HTTP methods. Explain with suitable example. [5 + 5]

Answer:

HTTP Methods:

 GET: Retrieves a resource.


 POST: Submits data to be processed to a specified resource.
 PUT: Replaces all current representations of the target resource with the request payload.
 DELETE: Deletes the specified resource.
 HEAD: Same as GET, but only retrieves the headers.
 OPTIONS: Describes the communication options for the target resource.
 TRACE: Performs a message loop-back test along the path to the target resource.
 CONNECT: Establishes a tunnel to the server identified by the target resource.

Examples:

 GET: GET /index.html HTTP/1.1


 POST: Submitting a form with user data.
 PUT: Uploading a file to a specific location on the server.
 DELETE: Deleting a blog post or a user account.

b) WAP of TCP client/server programs where:

 Client connects to the Server and sends some text.


 Server reverts that text backwards and sends it back to the Client.
 Program ends when Client types in "EXIT" (or "exit").

Server Code (ReverseTextServer.java):

Java
import java.io.*;
import java.net.*;
public class ReverseTextServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Reverse Text Server started on port 8080...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

String clientMessage;
while ((clientMessage = in.readLine()) != null) {
if (clientMessage.equalsIgnoreCase("EXIT")) {
break;
}
String reversedMessage = new
StringBuilder(clientMessage).reverse().toString();
out.println(reversedMessage);
}
System.out.println("Client disconnected.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client Code (ReverseTextClient.java):

Java
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ReverseTextClient {


public static void main(String[] args) {
try (Socket socket = new Socket("127.0.0.1", 8080);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in)) {

String userInput;
while (true) {
System.out.print("Enter text (or EXIT): ");
userInput = scanner.nextLine();
out.println(userInput);

if (userInput.equalsIgnoreCase("EXIT")) {
break;
}

String reversedMessage = in.readLine();


System.out.println("Reversed: " + reversedMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
c) WAP to Send and Receive a Message using Connectionless Sockets. (The datagram receiver program
illustrated that can receive a datagram packet of size at most 40 bytes.)

Server Code (UDPServer40.java):

Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer40 {


public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(9876)) {
byte[] buffer = new byte[40]; // Buffer size of 40 bytes
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

System.out.println("UDP Server started on port 9876...");


socket.receive(packet);

String message = new String(packet.getData(), 0, packet.getLength()).trim();


System.out.println("Received: " + message);

InetAddress address = packet.getAddress();


int port = packet.getPort();
String response = "Message Received";
byte[] responseBuffer = response.getBytes();
DatagramPacket responsePacket = new DatagramPacket(responseBuffer,
responseBuffer.length, address, port);
socket.send(responsePacket);

} catch (IOException e) {
e.printStackTrace();
}
}
}

Client Code (UDPClient40.java):

Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient40 {


public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket();
Scanner scanner = new Scanner(System.in)) {

InetAddress address = InetAddress.getByName("127.0.0.1");


int port = 9876;

System.out.print("Enter message (max 40 bytes): ");


String message = scanner.nextLine();
byte[] buffer = message.getBytes();

if (buffer.length > 40) {


System.out.println("Message too long. Truncating.");
buffer = message.substring(0, 40).getBytes();
}

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address,


port);
socket.send(packet);

byte[] responseBuffer = new byte[256];


DatagramPacket responsePacket = new DatagramPacket(responseBuffer,
responseBuffer.length);
socket.receive(responsePacket);

String response = new String(responsePacket.getData(), 0,


responsePacket.getLength()).trim();
System.out.println("Server: " + response);

} catch (IOException e) {
e.printStackTrace();
}
}
}

2024

Detailed Answers – Network Application Questions (Part 4)

1. Describe the process of reading the Header using URLConnection.

Process of Reading Headers Using URLConnection

The URLConnection class in Java is used to retrieve and read HTTP headers. The process involves the
following steps:

1. Create a URL Object: Define the URL you want to connect to.
2. Open a Connection: Use openConnection() to create a URLConnection object.
3. Connect to the Server: Call connect() to establish a connection.
4. Retrieve Header Fields: Use getHeaderField() and getHeaderFieldKey() to read the HTTP headers.

Example: Reading Headers from a URL


import java.net.*;
import java.io.*;

public class URLHeaderReader {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com"); // Replace with any URL
URLConnection conn = url.openConnection();
conn.connect();
// Print headers
int i = 1;
String header;
while ((header = conn.getHeaderField(i)) != null) {
System.out.println(conn.getHeaderFieldKey(i) + ": " + header);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Explanation:

 The program connects to a website and prints all HTTP headers.


 getHeaderFieldKey(i) gets the header name (e.g., Content-Type).
 getHeaderField(i) gets the header value (e.g., text/html).

2. Explain x-www-form-urlencoded Encoder and URI Decoder with Example.

a) x-www-form-urlencoded Encoder

 Used to encode form data before sending it via HTTP.


 Spaces are replaced with +, and special characters (=, &) are percent-encoded.
 Example: "Hello World!" → "Hello+World%21"

b) URI Decoder

 Used to decode percent-encoded data into a readable string.


 Example: "Hello+World%21" → "Hello World!"

Example: Encoding & Decoding in Java


import java.net.*;

public class URLEncoderDecoderExample {


public static void main(String[] args) {
try {
String original = "Hello World! @ Java";

// Encoding
String encoded = URLEncoder.encode(original, "UTF-8");
System.out.println("Encoded: " + encoded);

// Decoding
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Decoded: " + decoded);

} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Output:

Encoded: Hello+World%21+%40+Java
Decoded: Hello World! @ Java

3. Significance of HTTP Keep-Alive System Properties & Cookie Policy Program

Significance of HTTP Keep-Alive

 Keeps the TCP connection open for multiple requests.


 Reduces latency and overhead caused by frequent TCP handshakes.
 Can be controlled using Connection: keep-alive or Connection: close headers.

Program: Blocking .gov Cookies but Allowing Others


import java.net.*;
import java.util.List;
import java.util.Map;

public class CookieFilter {


public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com"); // Replace with any website
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

Map<String, List<String>> headers = conn.getHeaderFields();

// Filtering cookies
if (headers.containsKey("Set-Cookie")) {
for (String cookie : headers.get("Set-Cookie")) {
if (cookie.contains(".gov")) {
System.out.println("Blocked Cookie: " + cookie);
} else {
System.out.println("Allowed Cookie: " + cookie);
}
}
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Explanation:

 Fetches cookies from the response headers.


 Blocks cookies containing “.gov”.
 Allows cookies from other domains.
4. What is Java Secure Sockets Extension (JSSE)?

Definition:

 JSSE is a Java API for secure communication using SSL/TLS.


 Provides support for SSL sockets, HTTPS, and certificates.
 Used in secure banking, authentication, and encrypted communication.

Program: Creating Secure Sockets with tufoshss.edu.np


import javax.net.ssl.*;
import java.io.*;
import java.net.*;

public class SecureSocketExample {


public static void main(String[] args) {
try {
String hostname = "tufoshss.edu.np"; // Replace with a secure host
int port = 443; // HTTPS Port

SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();


SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port);

System.out.println("Connected to " + hostname + " securely.");


socket.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Explanation:

 Uses JSSE to establish an SSL connection.


 Works with any secure HTTPS website.

5. Explain Central Abstractions of Java NIO.

Java NIO (Non-blocking I/O) provides high-performance data processing. The main abstractions are:

1. Buffers – Store and manage data (e.g., ByteBuffer).


2. Channels – Transfer data efficiently (e.g., FileChannel).
3. Selectors – Handle multiple channels using a single thread.
4. Pipelines – Enable chaining of processing steps.

6. UDP Socket Options & Port Scanning Program

UDP Socket Options


Option Description

SO_BROADCAST Enables sending broadcast messages.

SO_TIMEOUT Sets timeout for receiving data.

SO_RCVBUF Sets receive buffer size.

SO_SNDBUF Sets send buffer size.

Program: Scanning Local UDP Ports from 1024 Upwards


import java.net.*;

public class UDPPortScanner {


public static void main(String[] args) {
for (int port = 1024; port <= 1100; port++) { // Scanning range
try {
DatagramSocket socket = new DatagramSocket(port);
System.out.println("Port " + port + " is free.");
socket.close();
} catch (Exception e) {
System.out.println("Port " + port + " is in use.");
}
}
}
}

✅ Explanation:

 Tries binding UDP sockets to ports.


 If a port is already in use, it prints a message.

7. Define Multicast Group & Working with Multicast Sockets

Definition of Multicast Group

 A Multicast Group allows sending data to multiple clients using one transmission.
 Uses Multicast IP (224.0.0.0 – 239.255.255.255).

How Multicast Works

1. Sender (Multicast Server) sends data to a multicast IP.


2. Multiple Clients (Multicast Receivers) join the group.
3. Clients receive the same message simultaneously.

Example: Multicast Socket Communication

Multicast Server
import java.net.*;

public class MulticastSender {


public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress group = InetAddress.getByName("224.0.0.1");
byte[] message = "Hello, Multicast!".getBytes();

DatagramPacket packet = new DatagramPacket(message, message.length, group, 5000);


socket.send(packet);
socket.close();
}
}

Multicast Client
import java.net.*;

public class MulticastReceiver {


public static void main(String[] args) throws Exception {
MulticastSocket socket = new MulticastSocket(5000);
InetAddress group = InetAddress.getByName("224.0.0.1");
socket.joinGroup(group);

byte[] buffer = new byte[256];


DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);

System.out.println("Received: " + new String(packet.getData()));


socket.close();
}
}

Detailed Answers – Network Application Questions (Part 5)

9. Explain Factory Method with Example & Write a Program to Download a


Webpage.

a) Explanation of Factory Method

 Factory Method is a creational design pattern that provides an interface for creating objects in a superclass but
allows subclasses to alter the type of objects that will be created.
 It helps achieve loose coupling, abstraction, and reusability.

Example: Factory Method Pattern in Java


// Step 1: Create an Interface
interface Computer {
void compute();
}

// Step 2: Create Concrete Classes


class Laptop implements Computer {
public void compute() {
System.out.println("Laptop is computing...");
}
}
class Desktop implements Computer {
public void compute() {
System.out.println("Desktop is computing...");
}
}

// Step 3: Create Factory Class


class ComputerFactory {
public static Computer getComputer(String type) {
if (type.equalsIgnoreCase("Laptop")) {
return new Laptop();
} else if (type.equalsIgnoreCase("Desktop")) {
return new Desktop();
}
return null;
}
}

// Step 4: Use Factory Method


public class FactoryMethodExample {
public static void main(String[] args) {
Computer comp1 = ComputerFactory.getComputer("Laptop");
comp1.compute();

Computer comp2 = ComputerFactory.getComputer("Desktop");


comp2.compute();
}
}

✅ Output:

Laptop is computing...
Desktop is computing...

🚀 Benefits:

 Reduces direct object instantiation.


 Allows flexibility for new object types.

b) Program to Download a Webpage


import java.io.*;
import java.net.*;

public class WebPageDownloader {


public static void main(String[] args) {
try {
String webURL = "https://www.example.com"; // Change URL as needed
URL url = new URL(webURL);
BufferedReader reader = new BufferedReader(new
InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new
FileWriter("downloaded_page.html"));

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}

reader.close();
writer.close();
System.out.println("Webpage downloaded successfully!");

} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Explanation:

 Opens a URL connection and reads the HTML content line by line.
 Saves the webpage content to a file (downloaded_page.html).

10. Key Differences Between Socket and ServerSocket & Console Chat Application
using TCP

a) Differences Between Socket and ServerSocket

Feature Socket ServerSocket

Purpose Used by client to establish a connection. Used by server to listen for incoming connections.
Socket socket = new Socket(host, ServerSocket server = new
Creation port); ServerSocket(port);

Usage Used for sending/receiving data. Accepts client connections via accept().

Connection One Socket per connection. Can handle multiple connections.

b) TCP Console Chat Application

🔹 Server Code

import java.io.*;
import java.net.*;

public class TCPChatServer {


public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(12345);
System.out.println("Server is running... Waiting for a client.");

Socket socket = server.accept();


System.out.println("Client connected.");

BufferedReader reader = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String message;

while (true) {
message = reader.readLine();
if (message.equalsIgnoreCase("exit")) {
System.out.println("Client disconnected.");
break;
}
System.out.println("Client: " + message);

System.out.print("You: ");
message = console.readLine();
writer.println(message);
}

socket.close();
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

🔹 Client Code

import java.io.*;
import java.net.*;

public class TCPChatClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
System.out.println("Connected to Server.");

BufferedReader reader = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

BufferedReader console = new BufferedReader(new InputStreamReader(System.in));


String message;

while (true) {
System.out.print("You: ");
message = console.readLine();
writer.println(message);

if (message.equalsIgnoreCase("exit")) {
System.out.println("Disconnected from server.");
break;
}

message = reader.readLine();
System.out.println("Server: " + message);
}

socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ How It Works:

 Server starts first, waits for a client.


 Client connects and starts two-way communication.
 Users can send messages, and typing exit will disconnect.

11. RMI Program to Calculate Area of a Triangle & List Network Interfaces

a) RMI Program to Calculate Area of a Triangle

🔹 Step 1: Create Remote Interface

import java.rmi.*;

public interface TriangleArea extends Remote {


double calculateArea(double base, double height) throws RemoteException;
}

🔹 Step 2: Implement the Interface

import java.rmi.server.*;

public class TriangleAreaImpl extends UnicastRemoteObject implements TriangleArea {


protected TriangleAreaImpl() throws RemoteException {
super();
}

public double calculateArea(double base, double height) {


return 0.5 * base * height;
}
}

🔹 Step 3: Create RMI Server

import java.rmi.*;
import java.rmi.registry.*;

public class RMIServer {


public static void main(String[] args) {
try {
TriangleAreaImpl obj = new TriangleAreaImpl();
LocateRegistry.createRegistry(1099);
Naming.rebind("TriangleAreaService", obj);
System.out.println("RMI Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}

🔹 Step 4: Create RMI Client


import java.rmi.*;

public class RMIClient {


public static void main(String[] args) {
try {
TriangleArea obj = (TriangleArea)
Naming.lookup("rmi://localhost/TriangleAreaService");
double area = obj.calculateArea(10, 5);
System.out.println("Area of Triangle: " + area);
} catch (Exception e) {
e.printStackTrace();
}
}
}

b) Program to List All Network Interfaces


import java.net.*;
import java.util.*;

public class ListNetworkInterfaces {


public static void main(String[] args) {
try {
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();

while (interfaces.hasMoreElements()) {
NetworkInterface netInt = interfaces.nextElement();
System.out.println("Interface: " + netInt.getName());
Enumeration<InetAddress> addresses = netInt.getInetAddresses();

while (addresses.hasMoreElements()) {
System.out.println(" Address: " + addresses.nextElement());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Output Example:

Interface: eth0
Address: 192.168.1.2
Address: fe80::1
Interface: lo
Address: 127.0.0.1

2023

Here are detailed answers with explanations and programs:


1. Client-Server Software Model & Java in Network Programming

a) Client-Server Software Model

 The client-server model is a distributed application structure that separates tasks between providers (servers)
and requesters (clients).
 Example: Web applications where browsers (clients) request data from web servers.

b) Strengths & Weaknesses of Java in Network Programming

Strengths Weaknesses

Platform-independent (Write once, run anywhere). Slightly slower than native languages like C/C++.

Built-in networking libraries (e.g., Socket, URL, InetAddress). Higher memory consumption.

Robust security features (Java Secure Socket Extension - JSSE). Requires JVM installation on client machines.

Supports both multi-threading and asynchronous I/O (NIO). Higher latency in real-time applications.

2. Use of InetAddress Class & Program to Retrieve IP & MAC Address

a) Use of InetAddress Class

 The InetAddress class represents an IP address in Java.


 It provides methods to retrieve local and remote IP addresses.

b) Program to Retrieve IP & MAC Address


import java.net.*;
import java.util.*;

public class IP_MAC_Address {


public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("IP Address: " + ip.getHostAddress());

NetworkInterface network = NetworkInterface.getByInetAddress(ip);


byte[] mac = network.getHardwareAddress();

StringBuilder macAddress = new StringBuilder();


for (byte b : mac) {
macAddress.append(String.format("%02X-", b));
}

System.out.println("MAC Address: " + macAddress.substring(0,


macAddress.length() - 1));

} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Output Example:

IP Address: 192.168.1.5
MAC Address: 3C-4A-92-AB-CD-01

3. URL Class & Program to Split URL into Parts

a) Definition of URL Class

 The URL (Uniform Resource Locator) class in Java represents a web address.
 It provides methods to extract different parts of a URL (protocol, domain, port, etc.).

b) Program to Split URL


import java.net.*;

public class URLSplitter {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com:8080/path/page.html?
query=java#section1");

System.out.println("Protocol: " + url.getProtocol());


System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Path: " + url.getPath());
System.out.println("Query: " + url.getQuery());
System.out.println("Ref (Fragment): " + url.getRef());

} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Output:

Protocol: https
Host: www.example.com
Port: 8080
Path: /path/page.html
Query: query=java
Ref (Fragment): section1

4. Definition of Socket & Differences Between TCP & UDP Sockets

a) Definition of Socket

 A socket is an endpoint in a network communication.


 Java provides the Socket class for TCP communication and DatagramSocket for UDP.

b) Differences Between TCP & UDP Sockets


Feature TCP Socket UDP Socket

Connection Connection-oriented (requires handshake). Connectionless (no handshake).

Reliability Reliable (ensures delivery & order). Unreliable (no guarantee of delivery).

Speed Slower (because of overhead). Faster (low overhead).

Use Case File transfer, messaging. Streaming, DNS queries.

5. Cookies & Program to Retrieve Stored Cookies

a) Definition of Cookies

 Cookies are small pieces of data stored by web browsers.


 They help in session management, personalization, and tracking.

b) Java Program to Retrieve Cookies


import java.net.*;
import java.util.List;
import java.util.Map;

public class CookieRetriever {


public static void main(String[] args) {
try {
CookieHandler.setDefault(new CookieManager());
URL url = new URL("https://www.example.com");

URLConnection conn = url.openConnection();


Map<String, List<String>> headers = conn.getHeaderFields();

for (String key : headers.keySet()) {


if ("Set-Cookie".equalsIgnoreCase(key)) {
System.out.println("Cookies: " + headers.get(key));
}
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Output:

Cookies: [sessionID=abc123; Path=/; HttpOnly]

6. IP Multicast & Program to Join a Multicast Group

a) Definition of IP Multicast

 IP Multicast is a method for sending data packets to multiple recipients simultaneously.


 Used in video streaming, stock market updates, and online gaming.
b) Java Program to Join a Multicast Group
import java.net.*;

public class MulticastJoin {


public static void main(String[] args) {
try {
MulticastSocket socket = new MulticastSocket(5000);
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.joinGroup(group);
System.out.println("Joined Multicast Group: " + group.getHostAddress());
socket.leaveGroup(group);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Output:

Joined Multicast Group: 230.0.0.1

7. Short Notes on (Any Two)

a) HTTP (Hypertext Transfer Protocol)

 Stateless protocol used for web communication.


 Works on port 80 by default.
 Uses methods like GET, POST, PUT, DELETE.
 HTTPS (secure HTTP) works over TLS/SSL.

b) RMI (Remote Method Invocation)

 Java RMI (Remote Method Invocation) allows invoking methods on remote objects.
 Uses rmiregistry for server-client communication.
 Supports distributed computing.
 Example: Online banking transactions.

c) Secure Socket (SSL/TLS)

 Provides secure communication over networks.


 Uses encryption to protect data (SSL/TLS).
 Java provides JSSE (Java Secure Socket Extension) for handling secure connections.
 Example: Secure login pages (HTTPS).
9. Multithreaded TCP Client and Server Socket Programs for Daytime Service

a) Multithreaded TCP Server (Daytime Service)

This server listens for client requests and sends the current date and time.

java
CopyEdit
import java.io.*;
import java.net.*;
import java.util.Date;

public class DaytimeServer {


public static void main(String[] args) {
int port = 5000;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Daytime Server started on port " + port);

while (true) {
Socket clientSocket = serverSocket.accept();
new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class ClientHandler extends Thread {


private Socket clientSocket;

public ClientHandler(Socket socket) {


this.clientSocket = socket;
}

public void run() {


try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String datetime = new Date().toString();
out.println("Current Date & Time: " + datetime);
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

b) TCP Client for Daytime Service

The client connects to the server and receives the current date and time.

java
CopyEdit
import java.io.*;
import java.net.*;

public class DaytimeClient {


public static void main(String[] args) {
String serverAddress = "localhost";
int port = 5000;
try (Socket socket = new Socket(serverAddress, port);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {

String serverResponse = in.readLine();


System.out.println("Server Response: " + serverResponse);

} catch (IOException e) {
e.printStackTrace();
}
}
}

✅ Run the server first, then run multiple clients to see the response.

10. UDP Client & Server to Identify Even or Odd Numbers

a) UDP Server (Even or Odd Identifier)

This server listens for a number from the client, checks if it's even or odd, and responds accordingly.

java
CopyEdit
import java.net.*;

public class UDPServer {


public static void main(String[] args) {
int port = 6000;
try (DatagramSocket serverSocket = new DatagramSocket(port)) {
System.out.println("UDP Server is running on port " + port);

byte[] receiveBuffer = new byte[1024];


DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);

while (true) {
serverSocket.receive(receivePacket);
String receivedData = new String(receivePacket.getData(), 0,
receivePacket.getLength());
int number = Integer.parseInt(receivedData.trim());
String response = (number % 2 == 0) ? "Even" : "Odd";

byte[] sendBuffer = response.getBytes();


DatagramPacket sendPacket = new DatagramPacket(
sendBuffer, sendBuffer.length, receivePacket.getAddress(),
receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

b) UDP Client
The client sends a number to the server and gets a response about whether it's even or odd.

java
CopyEdit
import java.net.*;
import java.util.Scanner;

public class UDPClient {


public static void main(String[] args) {
String serverAddress = "localhost";
int port = 6000;
try (DatagramSocket clientSocket = new DatagramSocket();
Scanner scanner = new Scanner(System.in)) {

System.out.print("Enter a number: ");


int number = scanner.nextInt();
byte[] sendBuffer = String.valueOf(number).getBytes();

InetAddress serverIP = InetAddress.getByName(serverAddress);


DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
serverIP, port);
clientSocket.send(sendPacket);

byte[] receiveBuffer = new byte[1024];


DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
clientSocket.receive(receivePacket);
String serverResponse = new String(receivePacket.getData(), 0,
receivePacket.getLength());

System.out.println("Server Response: The number is " + serverResponse);


} catch (Exception e) {
e.printStackTrace();
}
}
}

✅ Run the server first, then run the client and enter numbers to see the response.

11. Blocking vs. Non-Blocking I/O & Buffers and Channels in Java

a) Blocking vs. Non-Blocking I/O

Feature Blocking I/O Non-Blocking I/O

Behavior Waits until the operation completes. Doesn't wait; continues execution.

Performance Slower due to waiting. Faster due to async execution.

Thread Usage Each connection needs a separate thread. Uses a single thread for multiple connections.

Example InputStream.read(), Socket.accept() SelectableChannel, SocketChannel

✅ Example:

 Blocking I/O: socket.accept() waits for a client.


 Non-blocking I/O: socketChannel.configureBlocking(false); makes the socket non-blocking.

b) Handling Buffers & Channels in Java (NIO)

 Buffers: Store data before sending or after receiving.


 Channels: Provide efficient I/O operations.
 Types of Buffers: ByteBuffer, CharBuffer, IntBuffer, etc.

c) Example: Using ByteBuffer with FileChannel

This program writes data into a file using NIO (Non-blocking I/O).

java
CopyEdit
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class NIOBufferExample {


public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("example.txt");
FileChannel fileChannel = fos.getChannel()) {

ByteBuffer buffer = ByteBuffer.allocate(64);


buffer.put("Hello, Java NIO!".getBytes());

buffer.flip(); // Switch from writing to reading mode


fileChannel.write(buffer);
System.out.println("Data written to file successfully.");

} catch (IOException e) {
e.printStackTrace();
}
}
}

You might also like