0% found this document useful (0 votes)
7 views42 pages

Lab Manual

The document is a lab manual for the CS3591 Computer Networks course at Grace College of Engineering, detailing practical exercises for students in the B.Tech. Artificial Intelligence and Data Science program. It includes various exercises such as using network diagnostic commands, writing an HTTP web client, and implementing TCP socket applications like echo clients and chat applications. Additionally, it covers DNS simulation using UDP sockets and provides algorithms, procedures, and expected outputs for each exercise.

Uploaded by

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

Lab Manual

The document is a lab manual for the CS3591 Computer Networks course at Grace College of Engineering, detailing practical exercises for students in the B.Tech. Artificial Intelligence and Data Science program. It includes various exercises such as using network diagnostic commands, writing an HTTP web client, and implementing TCP socket applications like echo clients and chat applications. Additionally, it covers DNS simulation using UDP sockets and provides algorithms, procedures, and expected outputs for each exercise.

Uploaded by

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

4931_Grace College of Engineering, Thoothukudi

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA


SCIENCE

B.Tech. Artificial Intelligence and Data Science

Anna University Regulation: 2021

CS3591 – Computer Networks

II Year / IV Semester

Lab Manual

Prepared by HoD Principal

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

PRACTICAL EXERCISES: 30 PERIODS

1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute. Capture
ping and trace route PDUs using a network protocol analyzer and examine.

2. Write a HTTP web client program to download a web page using TCP sockets.

3. Applications using TCP sockets like: a) Echo client and echo server b) Chat

4. Simulation of DNS using UDP sockets.

5. Use a tool like Wireshark to capture packets and examine the packets

6. Write a code simulating ARP /RARP protocols.

7. Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using
NS.

8. Study of TCP/UDP performance using Simulation tool.

9. Simulation of Distance Vector/ Link State Routing algorithm.

10. Simulation of an error correction code (like CRC)

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

EX No.:1

Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute.
Capture ping and trace route PDUs using a network protocol analyzer and examine.

AIM:

 To understand and use basic network diagnostic commands.

 To capture and analyze network packets using a protocol analyzer.

 To examine PDUs of ping and traceroute commands.

THEORY:

 Network diagnostic commands are essential tools for analyzing and troubleshooting
network connectivity and performance.
 tcpdump: A command-line packet analyzer used to capture network packets and
display them in real-time.
 netstat: Displays network connections, routing tables, and interface statistics.
 ifconfig: Displays or configures a network interface on UNIX/Linux systems.
 nslookup: Queries DNS to obtain domain name or IP address mapping.
 traceroute: Displays the route packets take to reach a specified network host.

PROCEDURE:

1. tcpdump:

o Open terminal.

o Use the command: sudo tcpdump -i eth0

o Stop the capture using Ctrl + C.

o Analyze the captured packets.

2. netstat:

o Open terminal.

o Use the command: netstat -a to display all connections.

o Use netstat -r to display the routing table.

3. ifconfig:

o Open terminal.

o Use the command: ifconfig to display all active network interfaces.

o Use ifconfig eth0 down to disable an interface.

4. nslookup:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

o Open terminal.

o Use the command: nslookup www.google.com

o Observe the IP address returned by the DNS server.

5. traceroute:

o Open terminal.

o Use the command: traceroute www.google.com

o Observe the hops taken to reach the destination.

6. Packet Capture Using Wireshark:

o Open Wireshark.

o Start capturing on the network interface.

o Use the ping command: ping www.google.com

o Use the traceroute command: traceroute www.google.com

o Stop the capture and examine ICMP packets.

OUTPUT:

1. tcpdump output showing captured packets.

2. netstat output displaying network connections.

3. ifconfig output showing network interfaces.

4. nslookup output showing DNS query results.

5. traceroute output showing route details.

6. Wireshark capture displaying ICMP packets for ping and traceroute.

RESULT:

Network diagnostic commands were successfully executed, and packet captures


were analyzed using Wireshark.

Viva Questions:

1. What is the purpose of the tcpdump command?

2. How does netstat help in network analysis?

3. What information does ifconfig provide?

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

4. What is the role of nslookup in DNS resolution?

5. How does traceroute determine the path to a destination?

EX No.:2

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Write a HTTP web client program to download a web page using TCP sockets

AIM:

To write an HTTP client program to download a web page using TCP sockets.

ALGORITHM:

1. Import the socket module.

2. Define the web server and port (default HTTP port: 80).

3. Create a TCP socket.

4. Connect to the server.

5. Send an HTTP GET request.

6. Receive the response from the server.

7. Display the response.

8. Close the socket connection.

PROGRAM:

import socket

# Define the web server and port

host = "example.com"

port = 80

# Create a socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client_socket.connect((host, port))

# Send HTTP GET request

request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"

client_socket.send(request.encode())

# Receive and display the response

data = client_socket.recv(4096)

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

print(data.decode())

# Close the connection

client_socket.close()

OUTPUT:

HTTP/1.1 200 OK

Date: Mon, 12 Feb 2025 12:34:56 GMT

Content-Type: text/html; charset=UTF-8

...

<html>

<head><title>Example Domain</title></head>

<body>...</body>

</html>

RESULT:

The HTTP client program was successfully executed to retrieve a web page using TCP
sockets.

Explanation of the Program:

This Python program is an HTTP client that connects to a web server using TCP sockets to
fetch a web page.

1. Import the socket module

o The socket module in Python provides functions to create and manage


network connections.

2. Define the Web Server and Port

o host = "example.com" → Specifies the web server (you can replace this with
any other website).

o port = 80 → HTTP servers typically listen on port 80 for incoming requests.

3. Create a TCP Socket

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

o socket.AF_INET → Specifies an IPv4 address (Internet Protocol version 4).

o socket.SOCK_STREAM → Specifies a TCP connection (which is reliable and


connection-oriented).

4. Connect to the Web Server

o client_socket.connect((host, port)) → Establishes a connection between the


client and the web server.

5. Send an HTTP GET Request

o The request is formatted as:

GET / HTTP/1.1

Host: example.com

o "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"

 GET / → Requests the homepage (/) of the server.

 HTTP/1.1 → Uses HTTP version 1.1.

 Host: example.com → Specifies the target website.

 \r\n → Represents a newline (carriage return + line feed), necessary


in HTTP requests.

6. Receive the Server's Response

o data = client_socket.recv(4096)

o The client waits for the server's response, which contains the HTTP headers
and HTML content of the webpage.

7. Print the Response

o print(data.decode())

o The response is in bytes, so .decode() converts it into a readable string.

8. Close the Connection

o client_socket.close()

o This terminates the connection to free system resources.

Example Output Breakdown

 The response headers include:

HTTP/1.1 200 OK

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Date: Mon, 12 Feb 2025 12:34:56 GMT

Content-Type: text/html; charset=UTF-8

o 200 OK → Means the request was successful.

o Content-Type: text/html → Indicates that the response contains an HTML


web page.

 The HTML content follows, which can be rendered by a browser:

<html>

<head><title>Example Domain</title></head>

<body>...</body>

</html>

EX.No.:3 Applications using TCP sockets like: a) Echo client and echo server b) Chat

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Part A: Echo Client and Echo Server

AIM: To implement an Echo Client-Server model using TCP sockets.

ALGORITHM:

1. Create a server program that listens for incoming connections.

2. Accept client connections and receive messages.

3. Send back the same message to the client (echo).

4. Close the connection when done.

SERVER PROGRAM:

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.bind(("localhost", 12345))

server_socket.listen(1)

print("Server is listening...")

conn, addr = server_socket.accept()

print(f"Connection from {addr}")

data = conn.recv(1024)

print("Received:", data.decode())

conn.send(data) # Echo back the data

conn.close()

server_socket.close()

Client Program:

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client_socket.connect(("localhost", 12345))

message = "Hello, Server!"

client_socket.send(message.encode())

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

data = client_socket.recv(1024)

print("Received from server:", data.decode())

client_socket.close()

Output:

Server is listening...

Connection from ('127.0.0.1', 54321)

Received: Hello, Server!

Received from server: Hello, Server!

Part B: Chat Application

AIM: To implement a simple chat application using TCP sockets.

ALGORITHM:

1. Create a server that listens for incoming messages.

2. Create a client that sends messages to the server.

3. Display the exchanged messages.

4. Keep the chat running until one party disconnects.

SERVER PROGRAM:

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.bind(("localhost", 12346))

server_socket.listen(1)

print("Chat server started, waiting for connections...")

conn, addr = server_socket.accept()

print(f"Connected to {addr}")

while True:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

data = conn.recv(1024).decode()

if not data or data.lower() == "bye":

print("Chat ended by client.")

break

print("Client:", data)

reply = input("You: ")

conn.send(reply.encode())

if reply.lower() == "bye":

print("Chat ended.")

break

conn.close()

server_socket.close()

Client Program:

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client_socket.connect(("localhost", 12346))

print("Connected to chat server.")

while True:

message = input("You: ")

client_socket.send(message.encode())

if message.lower() == "bye":

print("Chat ended.")

break

data = client_socket.recv(1024).decode()

if not data or data.lower() == "bye":

print("Chat ended by server.")

break

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

print("Server:", data)

client_socket.close()

Output:

Chat server started, waiting for connections...

Connected to ('127.0.0.1', 54322)

Client: Hi there!

You: Hello!

Client: How are you?

You: I'm good, thanks!

Client: bye

Chat ended by client.

Result:

The Echo Client-Server model and chat application was successfully implemented using TCP
sockets.

Explanation

Part A: Echo Client and Echo Server

The Echo Server receives a message from the client and sends the same message back.

How it Works:

1. Server:

o Creates a TCP socket.

o Binds it to a specific address and port (localhost:12345).

o Listens for incoming connections.

o Accepts a connection from a client.

o Receives data and echoes it back.

o Closes the connection.

2. Client:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

o Creates a TCP socket.

o Connects to the server at localhost:12345.

o Sends a message to the server.

o Receives the echoed message.

o Closes the connection.

Part B: Chat Application

This is a two-way communication program where both client and server can send and
receive messages.

How it Works:

1. Server:

o Creates a TCP socket.

o Binds it to localhost:12346.

o Listens for client connections.

o Receives a message from the client.

o Sends a reply to the client.

o The chat continues until either party sends "bye".

2. Client:

o Creates a TCP socket.

o Connects to the server.

o Sends a message to the server.

o Receives and displays messages from the server.

o Continues chat until "bye" is sent.

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

 Echo Server → Sends back the same message received from the client.

 Chat Application → Enables two-way communication until "bye" is entered.

 Both programs use TCP sockets to establish reliable communication.

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

EX.NO.: 4 Simulation of DNS using UDP Sockets

AIM:

To simulate the working of DNS using UDP sockets in Cisco Packet Tracer and understand
how hostname resolution occurs.

ALGORITHM:

1. PC sends a UDP packet to the DNS server at port 53 with a domain name query.

2. DNS server checks its records for the domain name.

3. It replies with the corresponding IP address via UDP.

4. The PC then uses the IP for further communication.

THEORY:

 DNS translates human-friendly domain names into IP addresses.

 DNS uses UDP port 53 for queries.

 A DNS client sends a query to the DNS server, which replies with the IP.

DEVICES NEEDED:

 2 PCs (PC0, PC1)

 1 Server (Server0)

 1 Switch

 Copper Straight-Through cables

CONNECTIVITY DIAGRAM:

[PC0]------|

[Switch]------[Server]

[PC1]------|

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

STEPS TO SIMULATE DNS USING UDP IN CISCO PACKET TRACER:

1. Network Setup

 Drag and drop:

o 2 PCs (e.g., PC0 and PC1)

o 1 Server (will act as DNS server)

o 1 Switch

 Connect all devices using copper straight-through cables.

2. IP Configuration

 Click each device > Desktop > IP Configuration:

o PC0:
IP:192.168.1.10
Subnet:255.255.255.0 (Same for all below devices)
DNS: 192.168.1.100

o PC1:
IP:192.168.1.11
DNS: 192.168.1.100

o Server:
IP:192.168.1.100
DNS: 192.168.1.100

3. Configure DNS Server

 Click on Server > Services > DNS:

o Turn DNS ON

o Add a new record:

 Name: www.google.com

 Address: 192.168.1.100

4. Test DNS Resolution

 Click on PC0 or PC1 > Desktop > Web Browser

o Type: http://www. google.com

o It should open a page hosted on PC1 (if it's running a web service).

o OR use Command Prompt: nslookup www.example.com

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

SIMULATION SCREENS:

Setup

Output

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

EX. NO. 5 Use a tool like Wireshark to capture packets and examine the packets

AIM

To understand how network protocols work by capturing and analyzing packets using
Wireshark, a network protocol analyzer.

ALGORITHM:

1. Start Wireshark.

2. Select the correct network interface (e.g., Wi-Fi or Ethernet).

3. Begin capturing traffic.

4. Generate some traffic manually (e.g., open a website, ping a server).

5. Stop the capture after a few seconds.

6. Use filters (e.g., icmp, http, tcp) to analyze specific protocols.

7. Inspect individual packets to understand headers and payload.

8. Interpret protocol layers: Ethernet, IP, TCP/UDP, Application (HTTP, DNS, etc.).

9. Optionally, export the capture or save as .pcap file.

PROCEDURE (STEP-BY-STEP):

Step 1: Open Wireshark

 Launch Wireshark as administrator/root.

Step 2: Select a Network Interface

 Choose the correct interface (e.g., your Wi-Fi or Ethernet card).

 Click Start Capturing (blue fin icon).

Step 3: Generate Network Traffic

 Open a browser and visit http://httpforever.com/ or run ping 8.8.8.8 in


CMD/Terminal.

Step 4: Stop the Capture

 Click the red square icon after a few seconds of activity.

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Step 5: Apply Filters

Use filters in the top bar to isolate protocols:

 icmp – For ping packets

 http – For web traffic

 tcp.port == 80 – HTTP over TCP

 ip.addr == Filter by IP address

Step 6: Analyze Packets

 Click a packet → Expand the sections:

o Ethernet: MAC addresses

o IP: Source/Destination IPs

o TCP/UDP: Ports, flags

o HTTP/DNS: URL, query, response

Step 7: Save the Capture

 File → Save As → .pcapng file for later analysis or sharing.

Output Screens

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Viva Questions:

1. What is Wireshark?
2. What is packet capturing?
3. Why do we need a tool like Wireshark?
4. What is a .pcap or .pcapng file?
5. What are the basic layers you observe when analyzing a packet?

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

EX. NO. 6 Write a code simulating ARP /RARP protocols.

AIM

 To understand the working principles of ARP and RARP protocols.

 To simulate ARP and RARP protocols using Python.

 To learn how IP addresses are mapped to MAC addresses and vice versa.

THEORY:

Address Resolution Protocol (ARP):

ARP is a network layer protocol used to convert an IP address into a physical MAC address.
When a device wants to communicate with another device on the same network, it uses
ARP to find out the MAC address associated with the destination IP address.

Reverse Address Resolution Protocol (RARP):

RARP is used to map a MAC address to an IP address. It is mostly used by diskless


workstations that do not have their own IP address when they boot up.

ALGORITHM:

ARP Simulation:

1. Define a table with IP-MAC address mappings.

2. Accept the input IP address from the user.

3. Check the table for the corresponding MAC address.

4. If the MAC address is found, display it.

5. If not, print that the IP address is not found.

RARP Simulation:

1. Define a table with MAC-IP address mappings.

2. Accept the input MAC address from the user.

3. Check the table for the corresponding IP address.

4. If the IP address is found, display it.

5. If not, print that the MAC address is not found.

PROGRAM CODE:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

# ARP/RARP Simulation

arp_table = {

'192.168.1.1': '00:14:22:01:23:45',

'192.168.1.2': '00:14:22:01:23:46',

'192.168.1.3': '00:14:22:01:23:47'

rarp_table = {v: k for k, v in arp_table.items()}

# ARP Simulation

def arp(ip):

if ip in arp_table:

print(f"MAC Address for {ip} is {arp_table[ip]}")

else:

print("IP Address not found")

# RARP Simulation

def rarp(mac):

if mac in rarp_table:

print(f"IP Address for {mac} is {rarp_table[mac]}")

else:

print("MAC Address not found")

# Main Function

if __name__ == '__main__':

print("1. ARP Simulation")

print("2. RARP Simulation")

choice = int(input("Enter your choice: "))

if choice == 1:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

ip = input("Enter IP Address: ")

arp(ip)

elif choice == 2:

mac = input("Enter MAC Address: ")

rarp(mac)

else:

print("Invalid Choice")

Explanation of the Code:

1. ARP Table Creation:

o A dictionary arp_table is created where keys are IP addresses, and values are
their corresponding MAC addresses.

2. RARP Table Creation:

o The rarp_table dictionary is created using dictionary comprehension by


reversing the key-value pairs of the arp_table.

3. ARP Function:

o The arp() function accepts an IP address as input and checks if the IP exists in
the arp_table.

o If found, it prints the corresponding MAC address.

o If not, it notifies the user that the IP address is not found.

4. RARP Function:

o The rarp() function accepts a MAC address as input and checks if the MAC
address exists in the rarp_table.

o If found, it prints the corresponding IP address.

o If not, it notifies the user that the MAC address is not found.

5. Main Function:

o Displays a menu for ARP and RARP simulations.

o Accepts user input to select the desired protocol.

o Calls the respective function based on user choice.

Output:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Case 1: ARP Simulation

Enter your choice: 1

Enter IP Address: 192.168.1.1

MAC Address for 192.168.1.1 is 00:14:22:01:23:45

Case 2: RARP Simulation

Enter your choice: 2

Enter MAC Address: 00:14:22:01:23:45

IP Address for 00:14:22:01:23:45 is 192.168.1.1

RESULT:

The ARP and RARP protocols were successfully simulated using Python.

Viva Questions:

1. What is the purpose of ARP?

2. How does RARP differ from ARP?

3. Why is RARP less commonly used today?

4. How does ARP work in IPv6 networks?

5. What are the alternatives to RARP in modern networks?

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

EX. NO. 7

Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using
NS.

AIM:

 To understand the basic working of Network Simulator (NS).

 To simulate congestion control algorithms using NS.

 To analyze the performance of congestion control algorithms.

THEORY:

Network Simulator (NS): Network Simulator (NS) is a discrete event simulator targeted
primarily for networking research. It provides support for simulation of TCP, routing, and
multicast protocols over wired and wireless networks.

Congestion Control Algorithms: Congestion control algorithms are used to prevent network
congestion by managing the amount of data that can be transmitted. Common congestion
control algorithms include:

 Leaky Bucket Algorithm

 Token Bucket Algorithm

 TCP Tahoe

 TCP Reno

 Random Early Detection (RED)

ALGORITHM:

Simulation Steps:

1. Install NS-2 or NS-3 simulator on the system.

2. Define network topology using TCL (Tool Command Language) script.

3. Set up nodes and links with necessary parameters such as bandwidth and delay.

4. Configure TCP or UDP traffic agents between source and destination nodes.

5. Apply congestion control algorithms in the network.

6. Run the simulation.

7. Analyze the trace files for performance evaluation.

PROGRAM CODE (SAMPLE TCL SCRIPT FOR TCP CONGESTION CONTROL SIMULATION):

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

# Define Network Simulator Instance

set ns [new Simulator]

# Define Trace and NAM Files

set tracefile [open congestion.tr w]

$ns trace-all $tracefile

set namfile [open congestion.nam w]

$ns namtrace-all $namfile

# Create Nodes

set n0 [$ns node]

set n1 [$ns node]

# Create Link between Nodes with Bandwidth and Delay

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

# Define TCP Agent and Traffic

set tcp [new Agent/TCP]

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]

$ns attach-agent $n1 $sink

$ns connect $tcp $sink

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ftp set type_ FTP

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

# Schedule Events

$ns at 0.1 "$ftp start"

$ns at 4.0 "$ftp stop"

$ns at 5.0 "finish"

proc finish {} {

global ns tracefile namfile

$ns flush-trace

close $tracefile

close $namfile

exec nam congestion.nam &

exit 0

# Run Simulation

$ns run

OUTPUT:

1. The simulation will generate trace files and NAM files.

2. The trace files contain detailed information about packet transmissions.

3. The NAM file provides a graphical representation of the network and packet flow.

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

RESULT:

The simulation of congestion control algorithms was successfully executed using NS, and the
network performance was analyzed.

Viva Questions:

1. What is the significance of congestion control in computer networks?

2. How does the Leaky Bucket algorithm differ from the Token Bucket algorithm?

3. What is the role of TCP in congestion control?

4. Explain the working of Random Early Detection (RED) algorithm.

5. What are the advantages of using NS for network simulations?

EX. NO. 8

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Study of TCP/UDP performance using Simulation tool.

AIM:

 To understand the performance differences between TCP and UDP protocols.

 To simulate TCP and UDP protocols using a network simulation tool.

 To analyze the performance of both protocols under different network conditions.

THEORY:

Transmission Control Protocol (TCP):

TCP is a connection-oriented protocol that provides reliable data transfer by ensuring


data packets are delivered in order and without errors. It uses flow control, error checking,
and congestion control mechanisms.

User Datagram Protocol (UDP):

UDP is a connectionless protocol that provides faster data transmission without


guaranteeing delivery or order. It is suitable for applications where speed is more critical
than reliability, such as video streaming and online gaming.

ALGORITHM:

1. Install and configure the Network Simulator (NS-2 or NS-3).

2. Define the network topology using TCL (Tool Command Language) script.

3. Create nodes and establish links with specified bandwidth and delay.

4. Attach TCP and UDP agents to the nodes.

5. Generate traffic using FTP for TCP and CBR (Constant Bit Rate) for UDP.

6. Run the simulation.

7. Analyze the generated trace files to evaluate performance metrics such as


throughput, packet delivery ratio, and delay.

PROGRAM CODE (SAMPLE TCL SCRIPT FOR TCP/UDP PERFORMANCE):

# Create Simulator Instance

set ns [new Simulator]

# Define Trace and NAM Files

set tracefile [open tcp_udp.tr w]

$ns trace-all $tracefile

set namfile [open tcp_udp.nam w]

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

$ns namtrace-all $namfile

# Create Nodes

set n0 [$ns node]

set n1 [$ns node]

# Define Links with Bandwidth and Delay

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

# TCP Agent Setup

set tcp [new Agent/TCP]

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]

$ns attach-agent $n1 $sink

$ns connect $tcp $sink

set ftp [new Application/FTP]

$ftp attach-agent $tcp

# UDP Agent Setup

set udp [new Agent/UDP]

$ns attach-agent $n0 $udp

set null [new Agent/Null]

$ns attach-agent $n1 $null

$ns connect $udp $null

set cbr [new Application/Traffic/CBR]

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

$cbr attach-agent $udp

$cbr set packet_size_ 500

$cbr set rate_ 1Mb

# Schedule Events

$ns at 0.1 "$ftp start"

$ns at 1.0 "$cbr start"

$ns at 4.0 "$ftp stop"

$ns at 5.0 "$cbr stop"

$ns at 6.0 "finish"

proc finish {} {

global ns tracefile namfile

$ns flush-trace

close $tracefile

close $namfile

exec nam tcp_udp.nam &

exit 0

# Run Simulation

$ns run

OUTPUT:

1. The simulation will generate trace files containing packet transmission details.

2. The NAM file will visually display the network topology and data flow.

3. Performance metrics such as throughput and delay can be derived from the trace
files.

RESULT:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

The TCP and UDP performance was successfully simulated and analyzed using a network
simulation tool.

Viva Questions:

1. What are the key differences between TCP and UDP?

2. Which protocol is more reliable, and why?

3. What type of applications prefer UDP over TCP?

4. How does congestion control work in TCP?

5. What performance metrics are used to compare TCP and UDP?

Explanation of the Code:

1. Simulator Initialization:

o The Simulator instance is created to set up the simulation environment.

2. Trace and NAM File Creation:

o The simulator logs events to trace files and NAM files, which help visualize
the simulation.

3. Node Creation:

o Two nodes, n0 and n1, are created to simulate the sender and receiver.

4. Link Setup:

o A duplex link with 1Mbps bandwidth and 10ms delay is established between
the nodes using the DropTail queue management.

5. TCP Agent Setup:

o A TCP agent is attached to node n0, and a TCP sink agent is attached to node
n1.

o An FTP application generates traffic over the TCP connection.

6. UDP Agent Setup:

o A UDP agent is attached to node n0, and a Null agent (used to discard
packets) is attached to node n1.

o A CBR traffic generator is configured to send data over the UDP connection.

7. Event Scheduling:

o The FTP application starts at 0.1s and stops at 4.0s.

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

o The CBR traffic starts at 1.0s and stops at 5.0s.

o The simulation ends at 6.0s.

8. Finish Procedure:

o The finish procedure flushes trace files, closes them, and launches the NAM
visualization tool.

9. Simulation Execution:

o The simulation is executed by calling $ns run.

EX. NO. 9

Simulation of Distance Vector/ Link State Routing algorithm.

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

AIM:

 To understand the working principles of Distance Vector and Link State Routing
algorithms.

 To simulate Distance Vector and Link State Routing algorithms using a network
simulation tool.

 To compare the performance of both algorithms in terms of convergence time and


routing efficiency.

THEORY:

Distance Vector Routing:

Distance Vector Routing is a dynamic routing algorithm in which each router maintains a
table containing the distance to every other router in the network. The table is updated by
exchanging information with neighboring routers periodically.

Link State Routing:

Link State Routing is a dynamic routing algorithm in which each router maintains information
about the entire topology of the network. Each router independently computes the shortest
path to every other router using Dijkstra's algorithm.

ALGORITHM:

Distance Vector Routing Steps:

1. Initialize the distance table with direct neighbor costs.

2. Exchange distance tables with immediate neighbors.

3. Update the table based on received information.

4. Repeat the exchange and update process until convergence.

Link State Routing Steps:

1. Discover neighbors and measure link costs.

2. Broadcast link state information to all routers.

3. Build the complete topology of the network.

4. Apply Dijkstra's algorithm to compute the shortest path.

PROGRAM CODE (SAMPLE TCL SCRIPT FOR DISTANCE VECTOR ROUTING SIMULATION):

# Create Simulator Instance

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

set ns [new Simulator]

# Define Trace and NAM Files

set tracefile [open routing.tr w]

$ns trace-all $tracefile

set namfile [open routing.nam w]

$ns namtrace-all $namfile

# Create Nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

# Define Links

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

$ns duplex-link $n1 $n2 1Mb 10ms DropTail

$ns duplex-link $n0 $n2 1Mb 20ms DropTail

# Set Routing Protocol as Distance Vector

$ns rtproto DV

# Schedule Simulation Events

$ns at 0.1 "$n0 setdest 100 200 10"

$ns at 5.0 "finish"

proc finish {} {

global ns tracefile namfile

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

$ns flush-trace

close $tracefile

close $namfile

exec nam routing.nam &

exit 0

# Run Simulation

$ns run

Explanation of the Code:

1. Simulator Initialization:

o The Simulator instance is created to manage the simulation.

2. Trace and NAM File Creation:

o The simulation generates trace and NAM files for analysis and visualization.

3. Node Creation:

o Three nodes are created to represent routers in the network.

4. Link Setup:

o Duplex links with specified bandwidth and delay are set between the nodes.

5. Routing Protocol Setup:

o The Distance Vector routing protocol is set using $ns rtproto DV.

6. Simulation Events:

o Node n0 is set to transmit data at time 0.1 seconds.

o The simulation ends at 5.0 seconds.

7. Finish Procedure:

o The finish procedure closes trace files and launches the NAM visualization
tool.

OUTPUT:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

1. The simulation will generate trace files with routing updates and data transmission
details.

2. The NAM file will display the network topology and packet flows.

3. Convergence time and route paths can be analyzed from the trace file.

RESULT:

The simulation of Distance Vector and Link State Routing algorithms was successfully
executed, and the performance was analyzed.

Viva Questions:

1. What is the difference between Distance Vector and Link State Routing?

2. How does Dijkstra's algorithm work in Link State Routing?

3. What are the advantages of Link State Routing over Distance Vector Routing?

4. What happens if a router goes down in Distance Vector Routing?

5. What is the convergence time in a routing algorithm?

EX. NO. 10

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

Simulation of an error correction code (like CRC)

AIM:

 To understand the concept of error detection and correction in data communication.

 To simulate the Cyclic Redundancy Check (CRC) error correction code.

 To analyze the performance of CRC in detecting and correcting errors.

THEORY:

Cyclic Redundancy Check (CRC): CRC is an error-detecting code commonly used in


digital networks and storage devices to detect accidental changes to raw data. The sender
appends a CRC checksum to the data, which is generated by dividing the data by a fixed
polynomial divisor. The receiver performs the same division and checks if the remainder is
zero, indicating error-free transmission.

Working Principle:

1. The binary data is divided by a predefined binary polynomial using modulo-2


division.

2. The remainder of this division is appended to the original data as the CRC checksum.

3. The receiver performs the same division on the received data.

4. If the remainder is zero, the data is considered error-free; otherwise, an error is


detected.

ALGORITHM:

1. Define the binary data and polynomial divisor.

2. Append zero bits (equal to the degree of the divisor) to the data.

3. Perform modulo-2 division on the extended data by the divisor.

4. Append the remainder to the original data as the CRC checksum.

5. Transmit the data with the CRC checksum.

6. Perform the same modulo-2 division at the receiver end.

7. Check the remainder for error detection.

PROGRAM CODE (SAMPLE CRC SIMULATION IN PYTHON):

def xor(a, b):

result = []

# XOR operation starting from index 1

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

for i in range(1, min(len(a), len(b))):

result.append('0' if a[i] == b[i] else '1')

return ''.join(result)

def mod2div(dividend, divisor):

pick = len(divisor)

tmp = dividend[:pick]

while pick < len(dividend):

if tmp[0] == '1':

tmp = xor(tmp, divisor) + dividend[pick]

else:

tmp = xor(tmp, '0'*len(tmp)) + dividend[pick]

pick += 1

if tmp[0] == '1':

tmp = xor(tmp, divisor)

else:

tmp = xor(tmp, '0'*len(tmp))

return tmp

def encodeData(data, divisor):

l_key = len(divisor)

appended_data = data + '0'*(l_key - 1)

remainder = mod2div(appended_data, divisor)

return data + remainder

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

# Example

data = "101010"

divisor = "1101"

print("Input Data: ", data)

print("Divisor: ", divisor)

# Encode data

encoded_data = encodeData(data, divisor)

print("Encoded Data with CRC: ", encoded_data)

Explanation of the Code:

1. XOR Function:

o Performs the XOR operation between two binary strings.

2. Modulo-2 Division:

o The mod2div() function performs binary division using XOR and returns the
remainder.

3. Encoding Function:

o The encodeData() function appends zero bits to the data and calculates the
CRC checksum using modulo-2 division.

4. Output:

o The input data, divisor, and encoded data with CRC are printed.

OUTPUT:

Input Data: 101010

Divisor: 1101

Encoded Data with CRC: 101010110

RESULT:

CS3591_COMPUTER NETWORKS
4931_Grace College of Engineering, Thoothukudi

The CRC error correction code was successfully simulated and verified using Python.

Viva Questions:

1. What is the purpose of CRC in data communication?

2. How does modulo-2 division differ from regular division?

3. Why is CRC preferred over parity checks?

4. Can CRC detect burst errors?

5. What is the role of the polynomial divisor in CRC?

CS3591_COMPUTER NETWORKS

You might also like