CN Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

EX.

NO:1 LEARN TO USE COMMANDS LIKE TCPDUMP, NETSTAT, IFCONFIG, NSLOOKUP


AND TRACEROUTE. CAPTURE PING AND TRACEROUTE PDUS USING A NETWORK
PROTOCOL ANALYZER AND EXAMINE
AIM: To Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute
1. Tcpdump

The tcpdump utility allows you to capture packets that flow within your network to assist in network
troubleshooting. The following are several examples of using tcpdump with different options. Traffic
is captured based on a specified filter.
Options Description
-D Print a list of network interfaces.
-i Specify an interface on which to capture.
-c Specify the number of packets to receive.
-v, -vv, -vvv Increase the level of detail (verbosity).
-w Write captured data to a file.
-r Read captured data from a file.

Many other options and arguments can be used with tcpdump. The following are somespecific
examples of the power of the tcpdump utility.

1. Display traffic between 2 hosts

To display all traffic between two hosts (represented by variables host1 and host2):# tcpdump host
host1 and host2
2. Display traffic from a source or destination host only

To display traffic from only a source (src) or destination (dst) host:# tcpdump src host
# tcpdump dst host

3. Display traffic for a specific protocol

Provide the protocol as an argument to display only traffic for a specific protocol, for example
tcp, udp, icmp, arp:

# tcpdump protocol

For example to display traffic only for the tcp traffic :

# tcpdump tcp

4. Filtering based on source or destination port


To filter based on a source or destination port:
# tcpdump src port ftp
# tcpdump dst port http

2. Netstat

Netstat is a common command line TCP/IP networking available in most versions of Windows,
Linux, UNIX and other operating systems. Netstat provides information and statistics about
protocols in use and current TCP/IP network connections. The Windows help screen
(analogous to a Linux or UNIX for netstat reads as follows:
Displays protocol statistics and current TCP/IP network connections.
NETSTAT -a -b -e -n -o -p proto -r -s -v interval

-a Displays all connections and listening ports.


Displays the executable involved in creating each connection or listening port. In
some cases well-known executables host multiple independent components, and in
these cases the sequence of components involved in creating the connection or
-b
listening port is displayed. In this case the executable name is in [] at the bottom,
on top is the component it called, and so forth until TCP/IP was reached. Note that
this option can be time-consuming and will fail unless you have sufficient
permissions.
-e Displays Ethernet statistics. This may be combined with the -s option.
-n Displays addresses and port numbers in numerical form.
-o Displays the owning process ID associated with each connection.
Shows connections for the protocol specified by proto; proto may be any of: TCP,
-p proto
UDP, TCPv6, or UDPv6. If used with the -s option to display per-protocol statistics,
proto may be any of: IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
-r Displays the routing table.
Displays per-protocol statistics. By default, statistics are shown for IP, IPv6, ICMP,
-s ICMPv6, TCP, TCPv6, UDP, and UDPv6; the -p option may be used to specify a
subset of the default.
When used in conjunction with -b, will display sequence of components involved
-v
increating the connection or listening port for all executables.
Redisplays selected statistics, pausing interval seconds between each display. Press
interval CTRL+C to stop redisplaying statistics. If omitted, netstat will print the current
configuration information once.

OUTPUT

Syntax

netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]

Parameters
Used without displays active TCP connections.
parameters
-a Displays all active TCP connections and the TCP and UDP ports
on which the computer is listening.
e Displays Ethernet statistics, such as the number of bytes and
packets sent and received. This parameter can be combined with -
s.
-n Displays active TCP connections, however,
addresses and port numbers are expressed
numerically and no attempt is made to determine
names.
-o Displays active TCP connections and includes the process ID
(PID) for each connection. You can find the application based on
the PID on the Processes tab in Windows Task Manager. This
parameter can be combined with -a, -n,
and -p.

-p Shows connections for the protocol specified by Protocol. In this


case, the Protocol can be tcp, udp, tcpv6, or udpv6. If this
parameter is used with -s to display statistics by protocol,
Protocol can be tcp, udp, icmp, ip, tcpv6, udpv6,icmpv6, or ipv6.
-s Displays statistics by protocol. By default, statistics are shown
for the TCP,UDP, ICMP, and IP protocols. If the IPv6 protocol
for Windows XP is installed, statistics are shown for the TCP
over IPv6, UDP over IPv6, ICMPv6, and IPv6
-r Displays the contents of the IP routing table. This is equivalent
to the route print command.
to Interval Redisplays the selected information every Interval seconds.
Press CTRL+C stop the redisplay. If this parameter is
omitted, netstat prints the selected
information only once.
/? Displays help at the command prompt.

3. Ifconfig

In Windows, ipconfig is a console application designed to run from the Windows command prompt.
This utility allows you to get the IP address information of a Windows computer. It also allows some control
over active TCP/IP connections. Ipconfig replaced the older winipcfg utility.

Using ipconfig

From the command prompt, type ipconfig to run the utility with default options. The outputof the default
command contains the IP address, network mask, and gateway for all physical and virtual network adapter

Syntax

ipconfig [/all] [/renew [Adapter]] [/release [Adapter]] [/flushdns] [/displaydns] [/registerdns] [/showclassid
Adapter] [/setclassid Adapter [ClassID]]

Parameters
Used without Displays the IP address, subnet mask, and default gateway for all
parameters adapters.
/all Displays the full TCP/IP configuration for all adapters.
Without this parameter, ipconfig displays only the IP address, subnet
mask, and default gateway values for each adapter. Adapters can
represent physical interfaces, such as installed network adapters, or
logical interfaces, such as dial-up connections.
Renews DHCP configuration for all adapters (if an adapter is not
/renew [Adapter] specified) or for a specific adapter if the Adapter parameter is
included. This parameter is available only on computers with adapters
that are configured to obtain an IPaddress automatically. To specify
an adapter name, type the adapter name that appears when you use
ipconfig without parameters.
/release [Adapter] Sends a DHCPRELEASE message to the DHCP server to release the
current DHCP configuration and discard the IP address configuration
for either all adapters (if an adapter is not specified) or for a specific
adapter if the Adapterparameter is included. This parameter disables
TCP/IP for adapters configured to obtain an IP address automatically.
To specify an adapter name,type the adapter name that appears when
you use ipconfig without parameters.
Flushes and resets the contents of the DNS client resolver cache.
During DNS troubleshooting, you can use this procedure to discard
/flushdns
negative cache entriesfrom the cache, as well as any other entries that
have been added dynamically.
Displays the contents of the DNS client resolver cache, which includes
both entries preloaded from the local Hosts file and any recently
/displaydns obtained resource records for name queries resolved by the computer.
The DNS Client service uses this information to resolve frequently
queried names quickly, before querying its configured DNS servers.
Initiates manual dynamic registration for the DNS names and IP
addresses that are configured at a computer. You can use this
/registerdns parameter to troubleshoot a failed DNS name registration or resolve a
dynamic update problem between a client and the DNS server without
rebooting the client computer. The DNS settings in the advanced
properties of the TCP/IP protocol determine which names are
registered in DNS.
Adapter Displays the DHCP class ID for a specified adapter. To see
/showclassid the DHCP class ID for all adapters, use the asterisk (*) wildcard
character in place of Adapter. This parameter is available only on
computers with adapters thatare configured to obtain an IP address
automatically.
Adapter [ClassID] Configures the DHCP class ID for a specified
adapter. To set the DHCP class ID for all adapters, use the asterisk (*)
/setclassid wildcard character in place of Adapter. This parameter is available
only on computers with adapters that are configured to obtain an IP
address automatically. If a DHCP class ID is not specified, the current
class ID is removed.
Examples:

Ipconfig To display the basic TCP/IP configuration for all adapters

ipconfig /all To display the full TCP/IP configuration for all adapters

ipconfig /renew "Local Area To renew a DHCP-assigned IP address configuration for


Connection" onlythe Local Area Connection adapter
ipconfig /flushdns To flush the DNS resolver cache when troubleshooting
DNSname resolution problems

ipconfig /showclassid Local To display the DHCP class ID for all adapters with names
that start with Local

ipconfig /setclassid "Local Area To set the DHCP class ID for the Local Area Connection
Connection" TEST adapter to TEST

4 . Nslookup

The nslookup (which stands for name server lookup) command is a network utility program
used to obtain information about internet servers. It finds name server informationfor domains by
querying the Domain Name System.

5 . traceroute

Traceroute is a network diagnostic tool used to track the pathway taken by a packet on an
IP network from source to destination. Traceroute also records the time taken for each hop the
packet makes during its route to the destination.
Traceroute uses Internet Control Message Protocol (ICMP) echo packets with variable time to live
(TTL) values. The response time of each hop is calculated. To guarantee accuracy, each hop is
queried multiple times (usually three times) to better measure the response of that particular hop.
tracert www.google.com

With the tracert command shown above, we're asking tracert to show us the path from thelocal
computer all the way to the network device with the hostname www.google.com.

Tracing route to www.google.com [209.85.225.104]over a maximum of 30 hops:


1 <1 ms <1 ms <1 ms 10.1.0.1
2 35 ms 19 ms 29 ms 98.245.140.1
3 11 ms 27 ms 9 ms te-0-3.dnv.comcast.net [68.85.105.201]
...
13 81 ms 76 ms 75 ms 209.85.241.37
14 84 ms 91 ms 87 ms 209.85.248.102
15 76 ms 112 ms 76 ms iy-f104.1e100.net [209.85.225.104]
Trace complete.
EX.NO:2 write a http web client program to download a web

page using tcp sockets.

Aim:

The aim of this program is to create a basic HTTP web client in Python using TCP sockets to

download a web page.

Algorithm:
Step 1: Start the program

Step 2: Define the target host, port, and page to download.

Step 3: Create a TCP socket using socket.socket() from the Python socket module.

Step 4: Use socket.connect() to establish a connection to the web server specified by the host and
port.

Step 5: Construct an HTTP GET request string containing the requested page and necessary headers

(like Host and Connection) and Send the HTTP request to the server using socket.send().

Step 6: Receive the HTTP response from the server in chunks using socket.recv() and Continue

receiving until no more data is available.

Step 7: Extract the headers and content from the HTTP response and Check the status code for

errors or redirections if necessary.

Step 8: Close the socket connection using socket.close().

Step 9: Print or handle the downloaded web page content as needed.

Step 10: Stop the program.

Program:

import socket
def download_web_page(host, port,
page): # Create a TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server


client_socket.connect((host,
port))

# Send HTTP GET request


request = f"GET {page} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
client_socket.send(request.encode())

# Receive the response


response = b""
while True:
data = client_socket.recv(4096)
if not data:
break
response += data

# Close the socket


client_socket.close()

# Extract the content from the response


content = response.split(b"\r\n\r\n", 1)[1]

return content.decode()

if name == " main ":


host = "www.google.com"
port = 80
page = "/"

web_page_content = download_web_page(host, port, page)


print(web_page_content)

Output:
EX.NO:3 Write a python program applications using TCP sockets
like: a) Echo client and Echo server b) Chat

A) Echo client and Echo server

Aim:

The aim of this program is to create a simple client-server application using TCP
sockets where the client sends a message to the server, and the server echoes the message
back to the client.

Algorithm:
Echo client:
module.
Step 1: Import the socket
Step 2: Define the server address ( SERVER_HOST ) and port ( SERVER_PORT ).
Step 3: Create a TCP socket object using socket.socket() .
Step 4: Connect to the server using connect() .
Step 5: Prompt the user to enter a message to send to the server.
Step 6: Send the message to the server using sendall() .
Step 7: Receive the echoed message from the server using recv() .
Step 8: Print the echoed message.
Step 9: Close the client connection using close().

Echo Server:
Step 1: Import the socket module.
Step 2: Define the server address ( SERVER_HOST ) and port (SERVER_PORT).
Step 3: Create a TCP socket object using socket.socket() .
Step 4: Bind the socket to the server address and port using bind().
Step 5: Listen for incoming connections using listen() .
Step 6: Accept incoming connections using accept() .
Step 7: Receive data from the client using recv() .
Step 8: If data is received, print it and send it back to the client using sendall().
Step 9: Close the client connection using close().

Program:

Echo Client:

import socket

# Define server address and port


SERVER_HOST = '127.0.0.1'
SERVER_PORT = 12345

# Create a socket object


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
client_socket.connect((SERVER_HOST, SERVER_PORT))

# Send data to the server


message = input("Enter message to send: ")
client_socket.sendall(message.encode())

# Receive data from the server


response = client_socket.recv(1024)
print(f"[*] Response from server: {response.decode()}")

# Close the connection


client_socket.close()

Echo Server:

import socket

# Define server address and port


SERVER_HOST = '127.0.0.1'
SERVER_PORT = 12345

# Create a socket object


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

# Bind the socket to the server address and port


server_socket.bind((SERVER_HOST, SERVER_PORT))

# Listen for incoming connections


server_socket.listen(1)
print(f"[*] Listening on {SERVER_HOST}:{SERVER_PORT}")

while True:
# Wait for a connection
client_socket, client_address = server_socket.accept()
print(f"[*] Accepted connection from {client_address[0]}:{client_address[1]}")

# Receive data from the client


data = client_socket.recv(1024)

if data:
print(f"Received data from client: {data.decode()}")
# Echo the received data back to the client
client_socket.sendall(data)
else:
print("[*] No data received from client")

# Close the client connection


client_socket.close()

Output:
B)Chat:

Aim:
The aim of this program is to create a TCP-based chat application where multiple clients can connect
to a server and exchange messages with each other. The server acts as a central hub, relaying
messages between clients.

Algorithm:
Server

Step 1: Import the socket module.


Step 2: Define the server address (SERVER_HOST) and port (SERVER_PORT).
Step 3: Create a socket object using socket.socket().
Step 4: Bind the socket to the server address and port using bind().
Step 5:Listen for incoming connections using listen().
Step 6: Accept incoming connections using accept() in a loop.
Step 7: Create a new thread to handle each client connection.
Step 8: In each client handling thread:
• Receive messages from the client using recv().
• Broadcast the received message to all connected clients except the sender.
• Continue receiving and broadcasting messages until the client disconnects.
Step 9 : Close the client socket when the client disconnects.
Step 10: Close the server socket when the server shuts down.

Client:

Step 1: Import the socket module.


Step 2: Define the server address (SERVER_HOST) and port (SERVER_PORT).
Step 3: Create a socket object using socket.socket().
Step 4: Connect to the server using connect().
Step 5: Start a thread to receive messages from the server.
Step 6: Continuously prompt the user for input.
Step 7: Send the user's input to the server using sendall().

Program:

Server:

import socket
import threading

# Server configuration
SERVER_HOST = '127.0.0.6'
SERVER_PORT = 12346

# List to hold client connections


clients = []

def handle_client(client_socket, client_address):


print(f"[*] New connection from {client_address}")
clients.append(client_socket)

while True:
try:
# Receive message from client
message = client_socket.recv(1024).decode()
if not message:
break

print(f"[*] Received message from {client_address}: {message}")

# Broadcast message to all clients


for c in clients:
if c != client_socket:
c.sendall(message.encode())
except Exception as e:
print(f"Error: {e}")
break

# Remove the client from the list


clients.remove(client_socket)
client_socket.close()
print(f"[*] Connection from {client_address} closed")

def start_server():
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the server address and port


server_socket.bind((SERVER_HOST, SERVER_PORT))

# Listen for incoming connections


server_socket.listen(5)
print(f"[*] Server listening on {SERVER_HOST}:{SERVER_PORT}")

while True:
# Accept incoming connection
client_socket, client_address = server_socket.accept()

# Handle client in a new thread


client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()

if name == " main ":


start_server()
Client:

import socket
import threading

# Server configuration
SERVER_HOST = '127.0.0.6'
SERVER_PORT = 12346

def receive_messages(client_socket):
while True:
try:
# Receive message from server
message = client_socket.recv(1024).decode()
print(message)
except Exception as e:
print(f"Error: {e}")
break

def start_client():
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server


client_socket.connect((SERVER_HOST, SERVER_PORT))
print(f"[*] Connected to server {SERVER_HOST}:{SERVER_PORT}")

# Start a thread to receive messages from the server


receive_thread = threading.Thread(target=receive_messages, args=(client_socket,))
receive_thread.start()

# Send messages to the server


while True:
message = input()
client_socket.sendall(message.encode())

if name == " main ":


start_client()

Output:
EX.NO:4 simulation of DNS using UDP sockets

Aim

To simulate a basic DNS server and client using UDP sockets to resolve domain
names to IP addresses.
Algorithm :

DNS Server
Step1:Create a UDP socket.
Step2:Bind the socket to a specific port.
Step3:Listen for incoming DNS queries.

Step4:When a query is received, parse the domain name from the query.
Step5:Look up the IP address associated with the domain name.

Send the IP address back to the client as a response


DNS Client:
Step1.Create a UDP socket.
Step2.Prepare a DNS query packet with the domain name to be resolved.
Step3.Send the query packet to the DNS server.

Step4.Wait for the response.


Step5.Extract the IP address from the response packet.

Program:

DNS Server:
import socket
dns_table={"www.google.com":"192.165.1.1",
"www.youtube.com":"192.165.1.2"}
s= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
print("starting server. ")
s.bind(("127.0.0.1",1234))
while True:
data,address=s.recvfrom(1024)
print(f"{address}wants to fetch data!")
data=data.decode()
ip=dns_table.get(data,"Not Found!").encode()
send=s.sendto(ip,address)
DNS Client:
import socket
hostname = socket.gethostname()
ipaddr = "127.0.0.1"
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
addr = (ipaddr,1234)
c="Y"
while c.upper()=="Y":
req_domain=input("Enter domain name for which the ip is needed:")
send=s.sendto(req_domain.encode(),addr)
data,address=s.recvfrom(1024)
reply_ip=data.decode().strip()
print(f"the ip for the domain name{req_domain}:{reply_ip}")
c = (input("continue?(y/n)"))
s.close()

Output:
Server:

C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\dnsserver.py

starting server....

('127.0.0.1', 63977)wants to fetch data!

('127.0.0.1', 63977)wants to fetch data!

Client:

C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\dnsclient.py

Enter domain name for which the ip is needed:

Enter domain name for which the ip is needed:www.google.com


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

To write a python program Use a tool like wiresharkto capture packets and examine

Algorithm
Step 1: DNS Server

Run the DNS server script provided earlier.

Step 2: DNS Client

Run the DNS client script provided earlier.

Step 3: Capture Packets with Wireshark

1. Open Wireshark.
2. Start capturing packets on the network interface you're using (e.g., Wi-Fi or Ethernet).
3. Perform DNS queries using the DNS client script.
4. Stop the packet capture in Wireshark.
5. Analyze the captured packets.

Examination:

Wireshark captures packets exchanged over the network. We will focus on UDP
packets between the client and server.

DNS Query Packet (Client to Server):


• Source IP: Client's IP address

• Destination IP: Server's IP address


• Source Port: Assigned by the client OS
• Destination Port: DNS server port (e.g., 12345)
• Packet Contents: DNS query packet containing the domain name to be resolved.
• Source IP: Server's IP address
• Destination IP: Client's IP address
• Source Port: DNS server port (e.g., 12345)
DNS Response Packet (Server to Client)
• Destination Port: Assigned by the client OS
Packet Contents: DNS response packet containing the resolved IP address

Program
import scapy.all as scapy

def packet_callback(packet):
if packet.haslayer(scapy.IP):
ip_src = packet[scapy.IP].src
ip_dst = packet[scapy.IP].dst
protocol = packet[scapy.IP].proto

print(f"IP Source: {ip_src}, IP Destination: {ip_dst}, Protocol: {protocol}")

if packet.haslayer(scapy.TCP):
src_port = packet[scapy.TCP].sport
dst_port = packet[scapy.TCP].dport
print(f"TCP Source Port: {src_port}, TCP Destination Port: {dst_port}")
elif packet.haslayer(scapy.UDP):
src_port = packet[scapy.UDP].sport
dst_port = packet[scapy.UDP].dport
print(f"UDP Source Port: {src_port}, UDP Destination Port: {dst_port}")
elif packet.haslayer(scapy.ICMP):
icmp_type = packet[scapy.ICMP].type
icmp_code = packet[scapy.ICMP].code
print(f"ICMP Type: {icmp_type}, ICMP Code: {icmp_code}")

# Start sniffing packets


scapy.sniff(prn=packet_callback, store=0)

output
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\55.py

IP Source: 192.168.69.136, IP Destination: 192.168.69.235, Protocol: 17

UDP Source Port: 49288, UDP Destination Port: 53

IP Source: 192.168.69.136, IP Destination: 192.168.69.235, Protocol: 17

UDP Source Port: 53181, UDP Destination Port: 53


IP Source: 192.168.69.136, IP Destination: 20.198.118.190, Protocol: 6

TCP Source Port: 63759, TCP Destination Port: 443

IP Source: 20.198.118.190, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63759

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63776, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63776

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63776, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63776

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63782

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63782

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63782

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6


TCP Source Port: 443, TCP Destination Port: 63782

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63782

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63782

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Port: 443

IP Source: 23.200.238.232, IP Destination: 192.168.69.136, Protocol: 6

TCP Source Port: 443, TCP Destination Port: 63782

IP Source: 192.168.69.136, IP Destination: 23.200.238.232, Protocol: 6

TCP Source Port: 63782, TCP Destination Po


EX.NO:6 Write a code simulating

ARP /RARP protocols

Aim:

ARP (Address Resolution Protocol): The aim of ARP is to map an IP

address to a MAC address within a local network.

RARP (Reverse Address Resolution Protocol):The aim of RARP is to map a MAC address to an IP
address within a local network.
Algorithm:

ARP Server:
Step1:Create a socket to listen for ARP requests.
Step2:When a request is received, parse the target IP address.
Step3:Check if the IP address is in the ARP cache.
Step4:If found, retrieve the corresponding MAC address and send an ARP response.
Step5:If not found, do not respond (or broadcast to find the MAC address).
ARP Client:
Step1:Create a socket to listen for RARP requests.

Step2:When a request is received, parse the target MAC address.


Step3:Check if the MAC address is in the RARP cache.
Step4:If found, retrieve the corresponding IP address and send a RARP response.
Step5:If not found, do not respond.

Step6:Create a socket to listen for RARP requests.

Step7:When a request is received, parse the target MAC address.


Step8:Check if the MAC address is in the RARP cache.
Step9:If found, retrieve the corresponding IP address and send a RARP response.
Step10:If not found, do not respond.
Program:
import time
class ARPTable:

def init (self):

self.table = {}

def add_entry(self, ip_address, mac_address):


class RARPProtocol:

def init (self, arp_table):

self.arp_table = arp_table

def send_request(self, mac_address):

print(f"Sending RARP request for MAC: {mac_address}")

time.sleep(1)

for ip, mac in self.arp_table.table.items():

if mac == mac_address:

print(f"Received RARP response: MAC: {mac_address}, IP: {ip}")

return

print("No response received.")

def main():

arp_table = ARPTable()

arp_table.add_entry("192.168.1.1", "00:11:22:33:44:55")

arp_table.add_entry("192.168.1.2", "AA:BB:CC:DD:EE:FF")

arp_protocol = ARPProtocol(arp_table)

rarp_protocol = RARPProtocol(arp_table)

# Simulate ARP request/response

arp_protocol.send_request("192.168.1.1")

arp_protocol.send_request("192.168.1.3")

# Simulate RARP request/response

rarp_protocol.send_request("00:11:22:33:44:55")

rarp_protocol.send_request("FF:EE:DD:CC:BB:AA")

if name == " main ":


main()
output:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\apr.py

Sending ARP request for IP: 192.168.1.1

Received ARP response: IP: 192.168.1.1, MAC: 00:11:22:33:44:55

Sending ARP request for IP: 192.168.1.3

No response received.

Sending RARP request for MAC: 00:11:22:33:44:55

Received RARP response: MAC: 00:11:22:33:44:55, IP: 192.168.1.1

Sending RARP request for MAC: FF:EE:DD:CC:BB:AA

No response received.

Process finished with exit code 0


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

Aim:
To write Study of simulating and simulation of congestion control using NS algorithm.

1. Algorithm:
Step1;Initialization:

• Initialize congestion window size (cwnd) to 1.


• Initialize slow start threshold (ssthresh) to a predefined value.

Step2:Congestion Avoidance Phase:

• Increase cwnd linearly by 1 for every ACK received until cwnd reaches ssthresh.

Step3:Slow Start Phase:

• If cwnd is less than or equal to ssthresh, double cwnd for every ACK received.

Step4:Congestion Detection:

• If a packet loss occurs, set ssthresh to half of cwnd (ssthresh = max(cwnd / 2, 1)) and
reset cwnd to 1. Enter the slow start phase.

Program:
class AIMD:
def init (self, cwnd_init=1, ssthresh=16):
self.cwnd = cwnd_init
self.ssthresh = ssthresh
self.last_ack = 0
self.congestion_state = 'slow_start'

def packet_acknowledged(self, ack_num):


if ack_num > self.last_ack:
self.last_ack = ack_num
if self.congestion_state == 'slow_start':
self.cwnd += 1
if self.cwnd >= self.ssthresh:
self.congestion_state = 'congestion_avoidance'
elif self.congestion_state == 'congestion_avoidance':
self.cwnd += 1 / self.cwnd

def packet_lost(self):
self.ssthresh = max(self.cwnd / 2, 1)
self.cwnd = 1
self.congestion_state = 'slow_start'

def simulate_transfer(num_packets, loss_packet_at=20):


congestion_control = AIMD()
packets_sent = 0
packets_acked = 0

for i in range(1, num_packets + 1):


packets_sent += 1
if i == loss_packet_at:
congestion_control.packet_lost()
continue
congestion_control.packet_acknowledged(i)
packets_acked += 1

print(f"Packets sent: {packets_sent}, Packets acknowledged: {packets_acked}")

if name == " main ":


simulate_transfer(num_packets=100, loss_packet_at=20)

output:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\congestion.py

Packets sent: 100, Packets acknowledged: 99

Process finished with exit code 0


EX.NO:8 Study of TCP/UDP performance using
Simulation tool
Aim: To study and compare the performance of TCP and UDP protocols in a
simulated network environment.

Algorithm:

Step1:Initialize the simulation parameters such as network latency, packet loss rate, and
bandwidth.
Step2:Create sender and receiver entities for both TCP and UDP.
Step3:Generate packets with random sizes and send them from the sender to the receiver.

Step4:Simulate the transmission process considering network conditions such as latency


and packet loss.
Step5:Measure the time taken for packet delivery and calculate throughput.
Step6:Compare the performance metrics between TCP and UDP.

Program:
import random

import simpy

class Network:

def init (self, env, latency, packet_loss_rate, bandwidth):

self.env = env

self.latency = latency

self.packet_loss_rate = packet_loss_rate

self.bandwidth = bandwidth

def send_packet(self, packet):

yield self.env.timeout(self.latency)

if random.random() > self.packet_loss_rate:

yield self.env.timeout(packet.size / self.bandwidth)


class Sender:

def init (self, env, network, protocol):

self.env = env

self.network = network

self.protocol = protocol

def send(self, receiver, packet):

yield self.env.process(self.network.send_packet(packet))

receiver.receive(packet)

class Receiver:

def init (self, env):

self.env = env

def receive(self, packet):

pass # Do something with the received packet

def simulate(protocol):

env = simpy.Environment()

network = Network(env, latency=10, packet_loss_rate=0.1, bandwidth=100) # Example values

sender = Sender(env, network, protocol)

receiver = Receiver(env)

for _ in range(100):

packet = Packet(size=random.randint(100, 1000))

env.process(sender.send(receiver, packet))

env.run()

class Packet:

def init (self, size):


self.size = size

if name == " main ":

print("Simulation of TCP performance:")

simulate("TCP")

print("\nSimulation of UDP performance:")

simulate("UDP")

Output:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\tcpudpper.py

Simulation of TCP performance:

Simulation of UDP performance:

Process finished with exit code 0


EX.NO:9 Simulation of Distance Vector/ Link State
Routing algorithm
Aim:
To write Distance Vector Routing is a distributed algorithm used in computer
networks to dynamically update routing tables between routers. The aim is to determine
the shortest path to each destination within the network, based on information
exchanged between neighboring routers.

Algorithm:

Step1:Initialization:

• Each router initializes its own routing table, including its direct neighbors and the
distances to reach them.
• Initially, each router assumes that it can reach all destinations directly.

Step2:Exchange of Distance Vectors:

• Periodically, each router sends its entire routing table (distance vector) to all of its
neighbors.
• Upon receiving a distance vector from a neighbor, a router updates its routing table
based on the information received.

Step3:Distance Vector Update:

• For each destination in the routing table, the router calculates the shortest distance
to that destination based on the received distance vectors from its neighbors.
• The router updates its routing table with the shortest distances and the next hop
router for each destination.

Step4:Iterative Process:

• Steps 2 and 3 are repeated iteratively until the routing tables stabilize, i.e., no
changes occur in the routing tables.
Step5:Handling Changes:
If a router detects a change in the network (e.g., link failure or a new router added), it
recalculates its routing table and notifies its neighbors of the change.
Neighboring routers update their routing tables accordingly, and the process
continues until stability is reached again.

Program:
class Node:
def init (self, name):
self.name = name
self.neighbors = {}
self.distance_vector = {}

def add_neighbor(self, neighbor, distance):


self.neighbors[neighbor] = distance

def update_distance_vector(self):
for neighbor, distance in self.neighbors.items():
self.distance_vector[neighbor] = distance

def print_distance_vector(self):
print(f"Distance vector for node {self.name}: {self.distance_vector}")

class Network:
def init (self):
self.nodes = {}

def add_node(self, name):


self.nodes[name] = Node(name)

def add_connection(self, node1, node2, distance):


self.nodes[node1].add_neighbor(node2, distance)
self.nodes[node2].add_neighbor(node1, distance)

def update_network(self):
for node in self.nodes.values():
node.update_distance_vector()

def print_network_state(self):
for node in self.nodes.values():
node.print_distance_vector()

def distance_vector_routing(network, iterations):


for i in range(iterations):
network.update_network()
print(f"Iteration {i + 1}:")
network.print_network_state()

if name == " main ":


network = Network()

# Add nodes
network.add_node("A")
network.add_node("B")
network.add_node("C")

# Add connections
network.add_connection("A", "B", 1)
network.add_connection("A", "C", 5)
network.add_connection("B", "C", 3)

distance_vector_routing(network, iterations=5)

Output:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\distance.py

Iteration 1:

Distance vector for node A: {'B': 1, 'C': 5}

Distance vector for node B: {'A': 1, 'C': 3}

Distance vector for node C: {'A': 5, 'B': 3}

Iteration 2:

Distance vector for node A: {'B': 1, 'C': 5}

Distance vector for node B: {'A': 1, 'C': 3}

Distance vector for node C: {'A': 5, 'B': 3}

Iteration 3:

Distance vector for node A: {'B': 1, 'C': 5}

Distance vector for node B: {'A': 1, 'C': 3}

Distance vector for node C: {'A': 5, 'B': 3}

Iteration 4:

Distance vector for node A: {'B': 1, 'C': 5}

Distance vector for node B: {'A': 1, 'C': 3}


Distance vector for node C: {'A': 5, 'B': 3}

Iteration 5:

Distance vector for node A: {'B': 1, 'C': 5}

Distance vector for node B: {'A': 1, 'C': 3}

Distance vector for node C: {'A': 5, 'B': 3}

Process finished with exit code 0


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

Aim:

To write a Cyclic Redundancy Check (CRC) is a type of error-detecting code used in


digital networks and storage devices to detect accidental changes to raw data. The aim of
CRC is to generate a checksum (a fixed-size binary value) for a block of data that can be
appended to the data during transmission. Upon reception, the receiver recalculates the
checksum and compares it to the received checksum. If they match, it's likely that the data
was transmitted without errors; otherwise, an error may have occurred.

Algorithm:

Step1;Initialization:

• Select a CRC polynomial, typically represented as a binary number.


• Choose a fixed-size CRC checksum length.

Step2:Appending CRC Checksum:

• Append the CRC checksum to the data to be transmitted.

Step3:CRC Calculation:

• Treat the combined data (original data + CRC checksum) as a polynomial.


• Divide the polynomial by the CRC polynomial using modulo-2 division (XOR).
• The remainder obtained from the division becomes the CRC checksum.

Step4:Transmission:

• Transmit the data along with the CRC checksum.

Step5:Reception and Verification:

• Upon receiving the data and CRC checksum, the receiver appends the CRC checksum to
the received data.
• It performs the same CRC calculation as the sender (dividing the polynomial by the
CRC polynomial).
If the remainder obtained is zero, no errors are detected, and the data is accepted.
Otherwise, errors are detected, and appropriate action is taken (e.g., requesting
retransmission).
Program:
def crc_remainder(data, polynomial):
"""Calculate the CRC remainder of data using polynomial"""
crc = 0
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x80:
crc = (crc << 1) ^ polynomial
else:
crc <<= 1
return crc & 0xFF

def crc_generate(data, polynomial):


"""Generate CRC checksum for data using polynomial"""
crc = crc_remainder(data, polynomial)
return crc.to_bytes(1, 'big')

def crc_verify(data, checksum, polynomial):


"""Verify CRC checksum"""
crc = crc_remainder(data, polynomial)
return crc == checksum

if name == " main ":


# Example usage
data = b"Hello, world!"
polynomial = 0b100000111 # CRC-8 polynomial
checksum = crc_generate(data, polynomial)
print("Generated CRC checksum:", checksum.hex())

# Simulate transmission
received_data = data
received_checksum = checksum

# Verify CRC checksum


if crc_verify(received_data, received_checksum, polynomial):
print("CRC checksum verification successful. No errors detected.")
else:
print("CRC checksum verification failed. Errors detected.")
Output:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\errorcorrection.py

Generated CRC checksum: bc

CRC checksum verification failed. Errors detected.

Process finished with exit code 0

You might also like