CN Lab Manual
CN Lab Manual
CN Lab Manual
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.
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
Provide the protocol as an argument to display only traffic for a specific protocol, for example
tcp, udp, icmp, arp:
# tcpdump protocol
# tcpdump tcp
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
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.
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 /all To display the full TCP/IP configuration for all adapters
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.
Aim:
The aim of this program is to create a basic HTTP web client in Python using TCP sockets to
Algorithm:
Step 1: Start the program
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
Step 7: Extract the headers and content from the HTTP response and Check the status code for
Program:
import socket
def download_web_page(host, port,
page): # Create a TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return content.decode()
Output:
EX.NO:3 Write a python program applications using TCP sockets
like: a) Echo client and Echo server b) Chat
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
Echo Server:
import socket
while True:
# Wait for a connection
client_socket, client_address = server_socket.accept()
print(f"[*] Accepted connection from {client_address[0]}:{client_address[1]}")
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")
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
Client:
Program:
Server:
import socket
import threading
# Server configuration
SERVER_HOST = '127.0.0.6'
SERVER_PORT = 12346
while True:
try:
# Receive message from client
message = client_socket.recv(1024).decode()
if not message:
break
def start_server():
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
# Accept incoming connection
client_socket, client_address = server_socket.accept()
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)
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.
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....
Client:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\dnsclient.py
To write a python program Use a tool like wiresharkto capture packets and examine
Algorithm
Step 1: DNS Server
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.
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
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}")
output
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\55.py
Aim:
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.
self.table = {}
self.arp_table = arp_table
time.sleep(1)
if mac == mac_address:
return
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)
arp_protocol.send_request("192.168.1.1")
arp_protocol.send_request("192.168.1.3")
rarp_protocol.send_request("00:11:22:33:44:55")
rarp_protocol.send_request("FF:EE:DD:CC:BB:AA")
No response received.
No response received.
Aim:
To write Study of simulating and simulation of congestion control using NS algorithm.
1. Algorithm:
Step1;Initialization:
• Increase cwnd linearly by 1 for every ACK received until cwnd reaches ssthresh.
• 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_lost(self):
self.ssthresh = max(self.cwnd / 2, 1)
self.cwnd = 1
self.congestion_state = 'slow_start'
output:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\congestion.py
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.
Program:
import random
import simpy
class Network:
self.env = env
self.latency = latency
self.packet_loss_rate = packet_loss_rate
self.bandwidth = bandwidth
yield self.env.timeout(self.latency)
self.env = env
self.network = network
self.protocol = protocol
yield self.env.process(self.network.send_packet(packet))
receiver.receive(packet)
class Receiver:
self.env = env
def simulate(protocol):
env = simpy.Environment()
receiver = Receiver(env)
for _ in range(100):
env.process(sender.send(receiver, packet))
env.run()
class Packet:
simulate("TCP")
simulate("UDP")
Output:
C:\Users\Ara\PycharmProjects\pythonProject\venv\Scripts\python.exe
C:\Users\Ara\PycharmProjects\pythonProject\tcpudpper.py
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.
• 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.
• 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 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 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()
# 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:
Iteration 2:
Iteration 3:
Iteration 4:
Iteration 5:
Aim:
Algorithm:
Step1;Initialization:
Step3:CRC Calculation:
Step4:Transmission:
• 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
# Simulate transmission
received_data = data
received_checksum = checksum