0% found this document useful (0 votes)
5 views34 pages

RECORD

The document outlines various computer network commands and their functionalities, including Ping, Tracert, Ipconfig, Hostname, Nslookup, and Netstat, which are essential for network diagnostics and configuration. It also covers error detection techniques using CRC-CCITT, Bit Stuffing, Character Stuffing, and the Stop-and-Wait protocol for data transmission. Each section includes algorithms and example programs demonstrating the implementation of these concepts.

Uploaded by

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

RECORD

The document outlines various computer network commands and their functionalities, including Ping, Tracert, Ipconfig, Hostname, Nslookup, and Netstat, which are essential for network diagnostics and configuration. It also covers error detection techniques using CRC-CCITT, Bit Stuffing, Character Stuffing, and the Stop-and-Wait protocol for data transmission. Each section includes algorithms and example programs demonstrating the implementation of these concepts.

Uploaded by

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

22A81A0623 COMPUTER NETWORKS LAB

TASK-1
1. Study of basic network commands and Network configuration commands.
a) Ping
b) Tracert/Traceroute
c) Ipconfig / ifconfig
d) Hostname
e) Nslookup
f) Netstat
a) Ping Command:
The ping command is a network utility used to test the reachability of a host on an Internet
Protocol (IP) network and measure the round-trip time for messages sent from the source
to the destination. It helps diagnose network connectivity issues.
Syntax:
ping [options] <destination>
Key Features:
Sends ICMP Echo Request packets to the specified destination.
Receives ICMP Echo Reply packets to verify connectivity.
Measures the time (latency) it takes for packets to travel to the destination and back.
Helps detect packet loss and network performance issues.
Test Network Connectivity -- > ping google.com

1
22A81A0623 COMPUTER NETWORKS LAB

Setting no.of packets it should send (default=4) -- > ping -n 50 google.com

b) Tracert/Traceroute Command:
The tracert (Windows) or traceroute (Linux/macOS) command is a network diagnostic tool
used to track the path that packets take from a source to a destination across an IP
network. It helps identify network latency and locate connectivity issues.
Syntax:
tracert <destination>
Key Features:
Displays all intermediate routers (hops) between the source and destination.
Measures the time (latency) it takes for packets to reach each hop.
Helps identify network bottlenecks and failures.

2
22A81A0623 COMPUTER NETWORKS LAB

c) ipconfig/ifconfig Command:
The ipconfig (Windows) and ifconfig (Linux/macOS) commands are used to display and
manage network interface configuration details.
Syntax:
ipconfig [options]
Common usage:
ipconfig # Display basic network information
ipconfig /all # Show detailed network configuration
ipconfig /release # Release the current IP address
ipconfig /renew # Renew the IP address from DHCP
ipconfig /flushdns # Clear the DNS cache

3
22A81A0623 COMPUTER NETWORKS LAB

d) Hostname Command:
The hostname command is a simple utility used to display or change the hostname of a
computer on a network. A hostname is a unique identifier assigned to a computer or
device to distinguish it from others on a network.
Syntax:
hostname [options]
Common Usage:
1. Display the current hostname: hostname
2. Set a new hostname (requires admin/root privileges): hostname new-hostname
3. Display the fully qualified domain name (FQDN) (Linux/macOS): hostname -f

4
22A81A0623 COMPUTER NETWORKS LAB

e) Nslookup Command:
The nslookup (Name Server Lookup) command is a network utility used to query Domain
Name System (DNS) records to obtain domain name or IP address mappings. It helps
troubleshoot DNS issues by checking if a domain resolves correctly.
Syntax:
nslookup [options] [domain]
Common Usage:
1. Lookup an IP address for a domain: nslookup google.com
2. Reverse lookup (Find domain name from an IP address): nslookup 8.8.8.8
3. Query a specific DNS server: nslookup google.com 8.8.8.8
4. Get NS (Name Server) records of a domain: nslookup -query=NS google.com

f) Netstat Command:
The netstat (Network Statistics) command is used to display network connections, routing
tables, interface statistics, and more. It helps in diagnosing network issues and monitoring
system network activity.
Syntax:
netstat [options]
Common Usage:
1. Display all active network connections: netstat
2. Display all listening ports (TCP & UDP): netstat -a
3. Show detailed connection states and process IDs: netstat -ano
4. Display only listening ports: netstat -an | find "LISTEN"
5. Show network statistics (sent/received packets, errors, etc.): netstat -e
6. Display routing table information: netstat -r

5
22A81A0623 COMPUTER NETWORKS LAB

Proto – The protocol used (TCP or UDP).


Local Address – The IP address and port number of the local machine.
Foreign Address – The IP address and port number of the remote system.
State – The status of the connection (e.g., ESTABLISHED, TIME_WAIT, LISTENING, etc.).

Bytes – Total number of bytes received and sent.


Unicast packets – Packets sent/received that are directed to a single destination.

6
22A81A0623 COMPUTER NETWORKS LAB

Non-unicast packets – Broadcast or multicast packets.


Discards – Packets that were discarded but not due to errors (e.g., buffer issues).
Errors – Packets that encountered transmission or reception errors.
Unknown protocols – Received packets that were of an unrecognized protocol type.

Network Destination – The target network or IP address.


Netmask – Defines the range of the destination.
Gateway – The next-hop IP address through which packets are sent.
Interface – The local interface used for routing the packets.
Metric – A cost value; lower values indicate preferred routes.

7
22A81A0623 COMPUTER NETWORKS LAB

TASK-2
2. Construct Detecting error using CRC-CCITT
Error Detection Using CRC-CCITT
Cyclic Redundancy Check (CRC) is an error-detecting code used to detect accidental
changes in transmitted data. CRC-CCITT (16-bit) is a commonly used variant in
communication systems
Steps for Error Detection Using CRC-CCITT
1. Message Representation
The data (message) is represented as a binary polynomial.
2. Appending Zero Bits
Append 16 zeros to the message, corresponding to the degree of the CRC-CCITT
polynomial.
3. Polynomial Division
Perform binary division (modulo-2) between the message + zeros and the CRC-CCITT
generator polynomial.
4. Remainder Calculation
The remainder (16-bit CRC code) obtained from the division is appended to the original
message.
5. Transmission & Error Detection
The sender transmits message + CRC remainder.
The receiver performs the same division on the received data.
If the remainder is zero, the data is error-free.
If the remainder is non-zero, an error has been detected.
Program:
import java.io.*;
public class CRCGenerator {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Generator: ");
String gen = br.readLine();
System.out.println("Enter Data: ");

8
22A81A0623 COMPUTER NETWORKS LAB

String data = br.readLine();


String code = data;
while (code.length() < (data.length() + gen.length() - 1)) {
code = code + "0";
}
String crc = div(code, gen);
code = data + crc;
System.out.println("The Transmitted Code is: " + code);
System.out.println("Enter Received Code: ");
String rec = br.readLine();
System.out.println("Debug: Received Code = '" + rec + "'");
if (rec.isEmpty()) {
System.out.println("Received Code cannot be empty!");
return;
}
if (!rec.matches("[01]+")) {
System.out.println("Received Code must be a binary string (only 0s and 1s)!");
return;
}
String remainder = div(rec, gen);
if (remainder.isEmpty()) {
System.out.println("The Received Code cannot be accepted!");
} else if (Integer.parseInt(remainder) == 0) {
System.out.println("The Received Code can be accepted!");
} else {
System.out.println("The Received Code cannot be accepted!");
}
}
static String div(String num1, String num2) {
int cur = 0;

9
22A81A0623 COMPUTER NETWORKS LAB

StringBuilder remainder = new StringBuilder(num1);


while (cur <= remainder.length() - num2.length()) {
for (int i = 0; i < num2.length(); i++) {
remainder.setCharAt(cur + i, (char) ((remainder.charAt(cur + i) ^ num2.charAt(i)) +
'0'));
}
while (cur < remainder.length() && remainder.charAt(cur) == '0') {
cur++;
}
}
return remainder.substring(cur).isEmpty() ? "0" : remainder.substring(cur);
}
}

Output:

10
22A81A0623 COMPUTER NETWORKS LAB

TASK-3
3. Implementation of Bit Stuffing
Implementation of Bit Stuffing
Bit stuffing is a data transmission technique used to prevent confusion between data bits
and control signals. It ensures that a special pattern (e.g., a flag) used for frame boundaries
is not mistakenly interpreted as part of the actual data.
Bit Stuffing Algorithm
Sender Side:
When five consecutive 1s appear in the data, insert a 0 after them.
This prevents confusion with the frame delimiter (e.g., 01111110 in HDLC).
Receiver Side:
If five consecutive 1s are detected, and the next bit is 0, remove the 0.
This recovers the original data.
Use Cases

✅ Used in HDLC (High-Level Data Link Control).

✅ Ensures frame synchronization in network protocols.

✅ Prevents misinterpretation of control flags.

Example:
Input Data (Before Bit Stuffing)
0111110111111011110
Bit-Stuffed Data (Transmitted Frame)
011111010111110011111010
(Note: 0s are inserted after five 1s)

11
22A81A0623 COMPUTER NETWORKS LAB

Program:
import java.util.*;
public class BitStuffing2 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Input Data: ");
String data = sc.nextLine();
String stuffedData = BitStuffing(data);
System.out.println("Stuffed Data Sequence: " + stuffedData);
String unstuffedData = BitUnstuffing(stuffedData);
System.out.println("Unstuffed Data Sequence: " + unstuffedData);
}
public static String BitStuffing(String data) {
int count = 0;
int n = data.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) {
if (data.charAt(i) == '1') {
count++;
} else {
count = 0;
}
sb.append(data.charAt(i));
if (count == 5) {
sb.append('0');
count = 0;
}
}
return sb.toString();

12
22A81A0623 COMPUTER NETWORKS LAB

}
public static String BitUnstuffing(String data) {
int count = 0;
int n = data.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) {
if (data.charAt(i) == '1') {
count++;
} else {
count = 0;
}
sb.append(data.charAt(i));
if (count == 5) {
// Skip the next '0' as it was stuffed
i++;
count = 0;
}
}
return sb.toString();
}
}

Output:

13
22A81A0623 COMPUTER NETWORKS LAB

TASK-4
4. Implementation of Character Stuffing
Implementation of Character Stuffing
Character stuffing is a data-link layer technique used to differentiate control characters
(like frame delimiters) from actual data. It is primarily used in byte-oriented protocols such
as PPP (Point-to-Point Protocol).
Character Stuffing Algorithm
Sender Side:
A special flag character (e.g., DLE STX for start and DLE ETX for end) is used to define the
frame boundaries.
If the flag character appears in the data, an escape character (DLE) is inserted before it.
Receiver Side:
When receiving data, if an escape character (DLE) is found before a flag character, the
escape character is removed, and the original data is restored.
Use Cases

✅ Used in byte-oriented protocols like PPP and BISYNC.

✅ Helps in frame synchronization in serial communication.

✅ Ensures special characters are not misinterpreted as frame boundaries.

Example
Given Data (Before Stuffing)
ABC DLE STX DATA DLE ETX XYZ
Character-Stuffed Data (Transmitted Frame)
DLE STX ABC DLE DLE STX DATA DLE DLE ETX XYZ DLE ETX
(Note: The DLE (Data Link Escape) character is added before DLE STX and DLE ETX inside
the data)

14
22A81A0623 COMPUTER NETWORKS LAB

Program:
import java.util.*;
class Stuff{
String Stuff(String o){
StringBuilder sb = new StringBuilder();
sb.append('F');
for(char c: o.toCharArray()){
if(c=='E' || c=='F'){
sb.append('E');
}
sb.append(c);
}
sb.append('F');
return sb.toString();
}
}
class Unstuff{
String Unstuff(String s){
StringBuilder res = new StringBuilder();
for(int i=1; i<s.length()-1; i++){
char ch = s.charAt(i);
if(ch=='E'){
i++;
if(i<s.length()-1){
res.append(s.charAt(i));
}
} else{
res.append(ch);
}

15
22A81A0623 COMPUTER NETWORKS LAB

}
return res.toString();
}
}
class CharStuffing{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter String: ");
String s = sc.nextLine();
Stuff st = new Stuff();
String stuffed = st.Stuff(s);
System.out.println("Stuffed String: "+stuffed);
Unstuff us = new Unstuff();
String unstuffed = us.Unstuff(stuffed);
System.out.println("Unstuffed String: "+unstuffed);
}
}

Output:

16
22A81A0623 COMPUTER NETWORKS LAB

TASK-5
5. Implementation of stop and wait protocol.
Implementation of Stop-and-Wait Protocol
The Stop-and-Wait Protocol is a simple flow control and error control mechanism in data
communication. It ensures that each frame sent by the sender is acknowledged by the
receiver before sending the next frame. This method is reliable but introduces delays
because the sender must wait for an acknowledgment (ACK) before transmitting the next
frame.
Working of Stop-and-Wait Protocol
Sender Side:
Sends one frame at a time.
Waits for an acknowledgment from the receiver.
If an acknowledgment is received, the sender sends the next frame.
If no acknowledgment is received (due to loss or error), the sender retransmits the same
frame after a timeout.
Receiver Side:
Receives a frame from the sender.
If the frame is correct, it sends an acknowledgment (ACK).
If the frame is lost or contains errors, it does not send an acknowledgment, prompting the
sender to retransmit.
Advantages

✅ Reliable Communication – Ensures every frame is received correctly.

✅ Error Detection – Lost or corrupted frames can be retransmitted.

✅ Simple Implementation – No need for complex buffering mechanisms.


Disadvantages

❌ High Delay – Sender must wait for an ACK before sending the next frame.

❌ Low Efficiency – Only one frame is in transit at a time, leading to low throughput.

17
22A81A0623 COMPUTER NETWORKS LAB

Program:
import java.util.*;
class StopAndWait {
public static void main(String[] args) {
Sender sender = new Sender();
Receiver receiver = new Receiver();
int totalFrames = 5; // Number of frames to send
for (int i = 1; i <= totalFrames; i++) {
sender.sendFrame(i, receiver);
}
}
}

class Sender {
Random random = new Random();
public void sendFrame(int frame, Receiver receiver) {
boolean acknowledged = false;
while (!acknowledged) {
System.out.println("Sender: Sending frame " + frame);
if (random.nextInt(10) < 8) { // Simulate 80% success rate
acknowledged = receiver.receiveFrame(frame);
} else {
System.out.println("Sender: Frame " + frame + " lost. Resending...");
}
}
}
}

18
22A81A0623 COMPUTER NETWORKS LAB

class Receiver {
Random random = new Random();
public boolean receiveFrame(int frame) {
if (random.nextInt(10) < 8) { // Simulate 80% ACK success rate
System.out.println("Receiver: Frame " + frame + " received. Sending ACK.");
return true;
} else {
System.out.println("Receiver: Frame " + frame + " received but ACK lost.");
return false;
}
}
}

Output:

19
22A81A0623 COMPUTER NETWORKS LAB

TASK-6
6. Implementation of Dijkstra’s algorithm
Implementation of Dijkstra’s Algorithm
Dijkstra’s Algorithm is a graph-based algorithm used to find the shortest path from a single
source vertex to all other vertices in a weighted graph. It works efficiently on graphs with
non-negative weights and is widely used in network routing, GPS navigation, and AI
pathfinding.
Working of Dijkstra’s Algorithm
1. Initialize
Assign a distance of 0 to the source node and ∞ (infinity) to all other nodes.
Maintain a priority queue (min-heap) to keep track of the next node with the shortest
known distance.
2. Process the Graph
Select the node with the smallest known distance from the priority queue.
Update the distances to its neighboring nodes if a shorter path is found.
Mark the selected node as visited (processed) and remove it from the queue.
3. Repeat Until All Nodes Are Processed
Continue the process until all nodes are visited or the shortest path to the destination
node is found.
Time Complexity
Using Priority Queue (Min-Heap) → O((V + E) log V)
Using Simple Arrays → O(V²)
Where V is the number of vertices and E is the number of edges.
Program:
import java.util.*;
class Dijkstra3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int V = sc.nextInt();

20
22A81A0623 COMPUTER NETWORKS LAB

int graph[][] = new int[V][V];


System.out.println("Enter adjacency matrix:");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
graph[i][j] = sc.nextInt();
}
}
System.out.print("Enter source vertex: ");
int source = sc.nextInt();
dijkstra(graph, V, source);
}
static void dijkstra(int graph[][], int V, int source) {
int dist[] = new int[V];
boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
visited[i] = false;
}
dist[source] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, visited, V);
visited[u] = true;
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] +
graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

21
22A81A0623 COMPUTER NETWORKS LAB

printSolution(dist, V);
}
static int minDistance(int dist[], boolean visited[], int V) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] < min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
static void printSolution(int dist[], int V) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < V; i++) {
System.out.println(i + " \t " + dist[i]);
}
}
}
Output:

22
22A81A0623 COMPUTER NETWORKS LAB

TASK-7
7. Implementation Distance vector algorithm.
Implementation of Distance Vector Routing Algorithm
The Distance Vector Routing Algorithm is a routing protocol used in computer networks to
determine the shortest path to all nodes in a network. Each router maintains a routing
table that stores the distance to every other router. This information is updated
periodically based on the updates received from neighboring routers.
Steps in the Distance Vector Algorithm
1. Initialize the Distance Table
Each router initializes a distance table (matrix) where:
The directly connected neighbors have known distances.
The distances to other routers are set to infinity (∞) if no direct link exists.
The diagonal entries (self-to-self distance) are 0.
2. Iterative Distance Updates
Each router checks whether the shortest path to a destination can be improved by going
through an intermediate router.
The update rule is:
D(i,j)=min(D(i,j),D(i,k)+D(k,j))
where:
D(i,j) = Distance from router i to router j
D(i,k)+D(k,j) = Distance from i to j via an intermediate router 𝑘
3. Convergence of Routing Tables
The process is repeated until the routing tables of all routers stop changing.
After convergence, each router has the shortest path to every other router.
Program:
import java.util.*;
public class DistanceVectorRouting {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of nodes: ");

23
22A81A0623 COMPUTER NETWORKS LAB

int n = sc.nextInt();
int[][] adjacencyMatrix = new int[n][n];
// Input adjacency matrix
System.out.println("Enter the adjacency matrix (use 0 for no edge):");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
adjacencyMatrix[i][j] = sc.nextInt();
}
}
int[][] distance = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
distance[i][j] = 0;
} else if (adjacencyMatrix[i][j] != 0) {
distance[i][j] = adjacencyMatrix[i][j];
} else {
distance[i][j] = Integer.MAX_VALUE;
}
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (distance[i][k] != Integer.MAX_VALUE && distance[k][j] !=
Integer.MAX_VALUE) {
distance[i][j] = Math.min(distance[i][j], distance[i][k] + distance[k][j]);
}
}

24
22A81A0623 COMPUTER NETWORKS LAB

}
}
System.out.printf("%-10s", "Node");
for (int i = 1; i <= n; i++) {
System.out.printf("%-10s", "To " + i);
}
System.out.println();
for (int source = 0; source < n; source++) {
System.out.printf("%-10s", "Node " + (source + 1));
for (int destination = 0; destination < n; destination++) {
if (distance[source][destination] == Integer.MAX_VALUE) {
System.out.printf("%-10s", "inf");
} else {
System.out.printf("%-10s", distance[source][destination]);
}
}
System.out.println();
}
}
}
Output:

25
22A81A0623 COMPUTER NETWORKS LAB

TASK-8
8. Implementation of Congestion control using leaky bucket algorithms
Implementation of Congestion Control Using Leaky Bucket Algorithm
The Leaky Bucket Algorithm is a traffic shaping and congestion control mechanism used in
computer networks to control the flow of data packets. It ensures that data is transmitted
at a steady rate, preventing congestion caused by bursts of data.
Working of the Leaky Bucket Algorithm
1. Bucket Representation:
The algorithm is visualized as a bucket with a fixed capacity.
Packets (data) arrive at varying rates and are stored in the bucket.
2. Steady Outflow:
The bucket leaks (transmits packets) at a constant rate.
If packets arrive too fast and exceed the bucket capacity, overflow occurs, and excess
packets are discarded.
3. Traffic Control:
The algorithm smooths out bursts of traffic.
It ensures that the network does not get overwhelmed by high-speed bursts.
Advantages

✅ Prevents congestion by controlling bursty traffic.

✅ Ensures fair bandwidth usage.

✅ Avoids buffer overflow in routers.


Disadvantages

❌ Packets may be discarded if the bucket is full.

❌ Not suitable for real-time applications with strict delay constraints.


Program:
import java.util.*;
class LeakyBucket {
private static final int BUCKET_SIZE = 512;
public static void bktInput(int packetSize, int outputRate) {

26
22A81A0623 COMPUTER NETWORKS LAB

if (packetSize > BUCKET_SIZE) {


System.out.println("\n\t\tBucket overflow");
} else {
try {
Thread.sleep(2000);
while (packetSize > outputRate) {
System.out.println("\n\t\tBytes outputted.");
packetSize -= outputRate;
Thread.sleep(2000);
}
if (packetSize > 0)
System.out.println("\n\t\tLast " + packetSize + " bytes sent");
System.out.println("\n\t\tBucket output successful");
} catch (InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
public class LeakyBucketAlgorithm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.print("Enter output rate: ");
int outputRate = scanner.nextInt();
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(2000);
int packetSize = random.nextInt(600);

27
22A81A0623 COMPUTER NETWORKS LAB

System.out.println("\nPacket no:" + i + " \tPacket size: " + packetSize);


LeakyBucket.bktInput(packetSize, outputRate);
} catch (InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
Output:

28
22A81A0623 COMPUTER NETWORKS LAB

TASK-9
9. Implementation using Socket TCP both client and server programs.
Implementation of TCP Socket Programming (Client-Server Model)
TCP (Transmission Control Protocol) is a connection-oriented protocol that ensures reliable
communication between a client and a server. TCP sockets are used for network
communication, where a server listens for incoming requests, and a client initiates a
connection.
Working of TCP Socket Communication
Server Side:
Creates a socket.
Binds the socket to an IP address and port.
Listens for incoming connections.
Accepts a client connection.
Exchanges data with the client.
Closes the connection.
Client Side:
Creates a socket.
Connects to the server using the IP address and port.
Sends a request to the server.
Receives a response from the server.
Closes the connection.
Advantages of TCP Socket Communication

✅ Ensures reliable, ordered, and error-checked data transmission.

✅ Used in applications like HTTP, FTP, email services, and real-time chat applications.

✅ Supports bi-directional communication.


Disadvantages

❌ Slower than UDP due to connection establishment overhead.

❌ Requires more resources compared to UDP.

29
22A81A0623 COMPUTER NETWORKS LAB

Program:
TCPServer.java
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String args[]){
int port = 8080;
try(ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("TCP Server is listening on port "+port);
while(true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
String message = input.readLine();
System.out.println("Received from client: "+message);
output.println("Server received: "+message);
socket.close();
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
TCPClient.java
import java.io.*;
import java.net.*;
public class TCPClient {

30
22A81A0623 COMPUTER NETWORKS LAB

public static void main(String args[]) {


String hostname = "localhost";
int port = 8080;
try(Socket socket = new Socket(hostname, port)) {
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String message = "Hello Server!";
output.println(message);
System.out.println("Sent to server: "+message);
String response = input.readLine();
System.out.println("Server Response: "+response);
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
Output:

31
22A81A0623 COMPUTER NETWORKS LAB

TASK-10
10. Implementation using Socket UDP both client and server programs
Implementation of UDP Socket Programming (Client & Server)
UDP (User Datagram Protocol) is a connectionless protocol where data is sent as
independent packets. Unlike TCP, it does not establish a connection before sending data.
Steps in UDP Communication
1. UDP Server:
Binds to a specific port and waits for incoming datagrams.
Listens continuously for messages from clients.
Upon receiving a message, it processes it and sends a response back.
2. UDP Client:
Does not establish a connection; simply sends a datagram to the server.
Waits for a response from the server after sending a request.
3. Data Transmission:
Data is sent as datagrams (packets).
If a packet is lost, no retransmission occurs unless handled at the application level.
Advantages of UDP Socket Communication

✅ Faster Communication

✅ Lower Latency

✅ Lightweight Protocol

✅ Supports Broadcasting & Multicasting


Disadvantages

❌ Unreliable Transmission

❌ No Congestion Control

❌ Not Suitable for Large Data Transfers


Program:
UDPServer.java
import java.net.*;

32
22A81A0623 COMPUTER NETWORKS LAB

public class UDPServer {


public static void main(String args[]) {
int port = 5000;
try (DatagramSocket socket = new DatagramSocket(port)) {
System.out.println("UDP Server is listening on port " + port);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket requestPacket = new DatagramPacket(buffer, buffer.length);
socket.receive(requestPacket);
String message = new String(requestPacket.getData(), 0,
requestPacket.getLength());
System.out.println("Received from client: " + message);
String response = "Server received: " + message;
byte[] responseData = response.getBytes();
DatagramPacket responsePacket = new DatagramPacket(responseData,
responseData.length,
requestPacket.getAddress(), requestPacket.getPort());
socket.send(responsePacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
UDPClient.java
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
String serverAddress = "localhost";
int serverPort = 5000;

33
22A81A0623 COMPUTER NETWORKS LAB

try (DatagramSocket socket = new DatagramSocket()) {


String message = "Hello, Server!";
byte[] buffer = message.getBytes();
InetAddress serverIP = InetAddress.getByName(serverAddress);
DatagramPacket requestPacket = new DatagramPacket(buffer, buffer.length,
serverIP, serverPort);
socket.send(requestPacket);
System.out.println("Sent to server: " + message);
byte[] responseBuffer = new byte[1024];
DatagramPacket responsePacket = new DatagramPacket(responseBuffer,
responseBuffer.length);
socket.receive(responsePacket);
String response = new String(responsePacket.getData(), 0,
responsePacket.getLength());
System.out.println("Server response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:

34

You might also like