Exp 1.
Implementation of different type of topologies using packet tracer.
Bus Topology
Mesh Topology
Star Topology
Ring Topology
Tree Topology
Hybird Topology
Exp 2.
3 Router Networks using RIP in packet tracer.
Configure the pcs with IPV4
Configuer router with IP address and subnet mask
Configure all router to each other
Assigning routers RIP routes
Verifying the network by pinging the IP
Successfully packet Transfer
Exp 3
Implement subnetting and find +ne subnet mask
import ipaddress
def subnet_calculator(ip_with_prefix):
try:
# Create an IPv4 network object using the input provided
network = ipaddress.ip_network(ip_with_prefix, strict=False)
# Display basic information
print(f"IP Address: {network.network_address}")
print(f"Subnet Mask: {[Link]}")
print(f"Number of Usable Hosts: {network.num_addresses - 2}") # -2 for network and
broadcast addresses
print(f"Network Address: {network.network_address}")
print(f"Broadcast Address: {network.broadcast_address}")
print(f"First Usable IP: {network.network_address + 1}")
print(f"Last Usable IP: {network.broadcast_address - 1}")
# Print all possible subnets
print("\nList of subnets in the network:")
for subnet in [Link]():
print(subnet)
except ValueError as e:
print(f"Error: {e}")
if __name__ == "__main__":
# User input for IP address and CIDR notation
ip_with_prefix = input("Enter an IP address with CIDR prefix (e.g., [Link]/24): ")
# Call the subnet calculator function
subnet_calculator(ip_with_prefix)
OUTPUT:
Exp 4.
Find suitable path for transmission using state/ Distance vector routing
protocol.
# Define the nodes in the network using letters
NODES = ['A', 'B', 'C', 'D']
# Initialize distance vectors for each node
# Each index represents the distance to other nodes
distance_vectors = [
[0, 2, 1, float('inf')], # Distances from Node A
[2, 0, 3, 1], # Distances from Node B, corrected
[1, 3, 0, 4], # Distances from Node C
[float('inf'), 1, 4, 0] # Distances from Node D
# Function to print distance vectors
def print_distance_vectors():
print("Current Distance Vectors:")
for i in range(len(NODES)):
print(f"Node {NODES[i]}: {distance_vectors[i]}")
# Function to update distance vectors
def update_distance_vectors():
for i in range(len(NODES)):
for j in range(len(NODES)):
for k in range(len(NODES)):
# Update distance if a shorter path is found
if distance_vectors[i][j] > distance_vectors[i][k] + distance_vectors[k][j]:
distance_vectors[i][j] = distance_vectors[i][k] + distance_vectors[k][j]
# Initial state of distance vectors
print_distance_vectors()
OUTPUT:
Exp 5.
Socket Programming using C/ C++/ JAVA
//Socket programming using java.
import [Link];
import [Link];
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8080);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, [Link]);
[Link](packet);
String message = new String([Link](), 0, [Link]());
[Link]("Client: " + message);
String response = "Message received";
[Link](new DatagramPacket([Link](), [Link](),
[Link](), [Link]()));
}
import [Link];
import [Link];
import [Link];
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String message = "Hello from client";
InetAddress serverAddress = [Link]("localhost");
[Link](new DatagramPacket([Link](), [Link](), serverAddress, 8080));
[Link]("Message sent: " + message);
byte[] buffer = new byte[1024];
DatagramPacket responsePacket = new DatagramPacket(buffer, [Link]);
[Link](responsePacket);
[Link]("Server: " + new String([Link](), 0,
[Link]()));
}
import [Link].*;
import [Link].*;
public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080);
[Link]("TCP server listening on port 8080");
while (true) {
Socket clientSocket = [Link]();
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
String message = [Link]();
[Link]("Client: " + message);
[Link]("Message received");
[Link]();
}
}
import [Link].*;
import [Link].*;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
String message = "Hello from client";
[Link](message);
[Link]("Message sent: " + message);
[Link]("Server: " + [Link]());
[Link]();
}
Exp 6.
TCP socket for wired network
a. Say Hello to each other
[Link] Transfer
[Link]
import socket
import os
HOST = '[Link]' # Binds to all network interfaces
PORT = 65433 # Use the same port as the client
def sanitize_filename(filename):
"""Remove unwanted characters from the filename."""
return [Link](filename)
def start_server():
with [Link](socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f"Server listening on {HOST}:{PORT}")
conn, addr = server_socket.accept()
with conn:
print(f"Connected by {addr}")
# Receive greeting message from client
greeting = [Link](1024).decode()
print(f"Client: {greeting}")
# Send a greeting back to the client
[Link](b'Hello from Server')
# Receive the filename from client and sanitize it
filename = [Link](1024).decode()
filename = sanitize_filename(filename)
print(f"Receiving file: {filename}")
# Send readiness acknowledgment
[Link](b'READY')
# Create folder for received files if it doesn't exist
save_path = [Link]("received_files", filename)
[Link]("received_files", exist_ok=True)
# Start receiving file data in chunks
with open(save_path, 'wb') as f:
while True:
chunk = [Link](1024)
if not chunk: # Exit if no more data
break
[Link](chunk)
print(f"File '{filename}' received and saved successfully.")
if __name__ == "__main__":
start_server()
a. [Link]
import socket
import os
HOST = '[Link]'
PORT = 65433
def start_client():
filename = r"D:\CN Practicals\practical 6\[Link]" # File to be sent
# Check if the file exists
if not [Link](filename):
print(f"Error: '{filename}' not found.")
return
with [Link](socket.AF_INET, socket.SOCK_STREAM) as client_socket:
try:
# Connect to the server
client_socket.connect((HOST, PORT))
print("Connected to the server!")
# Send greeting to the server
client_socket.sendall(b'Hello from Client')
response = client_socket.recv(1024).decode()
print(f"Server: {response}")
# Send filename to the server
client_socket.sendall([Link](filename).encode())
ack = client_socket.recv(1024).decode()
# Check if the server is ready for file transfer
if ack != "READY":
print("Server is not ready for file transfer.")
return
# Send file content in chunks
with open(filename, 'rb') as f:
while chunk := [Link](1024):
client_socket.sendall(chunk)
print("File sent successfully.")
except [Link] as e:
print(f"Connection error: {e}")
if __name__ == "__main__":
start_client()
b. tcp_server1.py
import socket
import os
import time
BUFFER_SIZE = 32
BUFFER_FILENAME = 1024
SERVER_IP = '[Link]'
SERVER_PORT = 12345
sock = [Link](socket.AF_INET, socket.SOCK_STREAM)
print(f'Starting server on {SERVER_IP}:{SERVER_PORT}')
# Bind and listen for incoming connections
[Link]((SERVER_IP, SERVER_PORT))
[Link](1)
while True:
print('Waiting for a connection...')
connection, client_addr = [Link]()
try:
print(f"Connected by {client_addr}")
start = [Link]() # Start time tracking for file upload
# Receive the filename from the client
file_name = [Link](BUFFER_FILENAME).decode()
file_name = [Link](file_name) # Sanitize the filename
# Open file to read in binary mode
try:
with open(file_name, 'rb') as fd:
print('Sending Data...')
# Read and send file data in chunks
while (buf := [Link](BUFFER_SIZE)):
[Link](buf)
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
[Link](b"ERROR: File not found.") # Send error to client if file is missing
continue
end = [Link]() # End time tracking for file upload
print(f"Time taken to upload: {end - start:.2f} seconds")
print(f"File '{file_name}' uploaded successfully.")
finally:
# Close the connection with the client
[Link]()
b. tcp_client1.py
import socket
import os
import time
BUFFER_SIZE = 32
HOST = '[Link]'
PORT = 12345
print("Enter the corresponding number to download a book:")
print("1. Atlas Shrugged by Ayn Rand")
print("2. Don Quixote by Miguel de Cervantes")
print("3. Shogun by James Clavell")
print("4. The Stand by Stephen King")
print("5. War and Peace by Leo Tolstoy")
file_number = int(input("Selection: "))
# Determine the filename based on user input
if file_number == 1:
file_name = "Atlas [Link]"
elif file_number == 2:
file_name = "Don [Link]"
elif file_number == 3:
file_name = "[Link]"
elif file_number == 4:
file_name = "The [Link]"
elif file_number == 5:
file_name = "War and [Link]"
else:
print("Invalid selection.")
exit()
# Prepare the socket connection
sock = [Link](socket.AF_INET, socket.SOCK_STREAM)
try:
print('Connecting to', HOST)
[Link]((HOST, PORT))
print('Connected')
# Send filename to the server
[Link](file_name.encode())
# Construct the new filename
base_name, extension = [Link](file_name)
new_file_name = f"{base_name}+Protocol=TCP+{[Link]()}{extension}"
# Start time tracking
start = [Link]()
# Open the new file to write data received from the server
with open(new_file_name, 'wb') as f:
print('Receiving Data')
# Receive data in chunks
while True:
byte = [Link](BUFFER_SIZE)
if not byte: # Break if no more data is received
break
[Link](byte) # Write received data to file
end = [Link]() # End time tracking
# Calculate the file size and throughput
file_size = [Link](new_file_name).st_size
throughput = round((file_size * 0.001) / (end - start), 3) # Throughput in kB/s
print(f"File '{new_file_name}' downloaded successfully.")
print(f"Time taken to download: {end - start:.2f} seconds")
print(f"Throughput: {throughput} kB/s")
finally:
[Link]() # Close the socket connection
Exp 7.
Perform HTTP, HTTPS AND FTP
Accessing the web pages with HTTP protocol
Accessing the web pages using HTTPS protocol
Configuring FTP on server
Upload the file [Link] created on PC1 to the server.
Upload the file [Link] created on PC2 to the server.
Download the file [Link] shared by PC2 onto PC1
Download the file [Link] shared by PC1 onto PC2
Exp.8
UDP Sockets to enable file transfer
UDP_server.py
import socket
import os
import time
BUFFER_SIZE = 32
BUFFER_FILENAME = 1024
SERVER_IP = '[Link]'
SERVER_PORT = 12345
sock = [Link](socket.AF_INET, socket.SOCK_DGRAM)
print('Starting server on port', SERVER_PORT)
[Link]((SERVER_IP, SERVER_PORT))
while True:
print('Waiting to receive message')
# Receive the filename from the client
file_name, client_addr = [Link](BUFFER_FILENAME)
print(client_addr, 'connected')
start = [Link]()
# Decode and prepare the file name
file_name = file_name.decode().strip()
file_name = [Link](file_name)
try:
# Open the file to read and send data
with open(file_name, 'rb') as fd:
print('Sending Data')
# Read and send file data in chunks
buf = [Link](BUFFER_SIZE)
while buf:
[Link](buf, client_addr)
buf = [Link](BUFFER_SIZE)
end = [Link]()
print(f"Time taken to upload: {end - start} sec")
print(file_name, "uploaded successfully")
except FileNotFoundError:
print(f"File {file_name} not found.")
[Link]()
UDP_client.py
import socket
import os
import time
BUFFER_SIZE = 32
HOST = '[Link]'
PORT = 12345
server_addr = (HOST, PORT)
# Display options for book selection
print("Enter the corresponding number to download book:")
print("1. Atlas Shrugged by Ayn Rand")
print("2. Don Quixote by Miguel de Cervantes")
print("3. Shogun by James Clavell")
print("4. The Stand by Stephen King")
print("5. War and Peace by Leo Tolstoy")
file_number = int(input())
if file_number == 1:
file_name = "Atlas [Link]"
elif file_number == 2:
file_name = "Don [Link]"
elif file_number == 3:
file_name = "[Link]"
elif file_number == 4:
file_name = "The [Link]"
elif file_number == 5:
file_name = "War and [Link]"
else:
print("Invalid selection.")
exit()
file = file_name.split('.')
# Set up UDP socket
sock = [Link](socket.AF_INET, socket.SOCK_DGRAM)
try:
start = [Link]()
# Send file name to server
[Link](file_name.encode(), server_addr)
# Create unique file name for the received file
file_name = file[0] + "+Protocol=UDP" + "+" + str([Link]()) + "." + file[1]
with open(file_name, 'wb') as f:
print('Receiving Data')
while True:
[Link](2) # Set a timeout for receiving data
try:
byte, server = [Link](BUFFER_SIZE)
if not byte:
break # End if no data received
[Link](byte) # Write data to file
except [Link]:
print("Timeout Occurred")
break
end = [Link]()
print(f"Time taken to download: {end - start} sec")
print("Downloaded", file_name)
# Calculate throughput
file_stat = [Link](file_name)
file_size = file_stat.st_size
throughput = round((file_size * 0.001) / (end - start), 3)
print("Throughput:", throughput, "kB/s")
finally:
[Link]()
Exp 9.
Learn email protocol using Microsoft Office Outlook
Exp. 10
To study IPsec protocol
Exp 11.
Installation and configuration of DHCP server.
Assign static IP to server – [Link] and assume gateway as
Configure DHCP on server
Assign IP address to both PC using DHCP.
Exp 12.
Program for DNS lookup
import socket
def dns_lookup(query):
try:
# Check if the input is a valid IP address
socket.inet_aton(query) # Validates IPv4 address
# Perform reverse DNS lookup (IP to URL)
host = [Link](query)
print(f"Domain name for IP '{query}': {host[0]}")
except [Link]:
# If it's not a valid IP, assume it's a domain and perform DNS lookup
try:
ip_address = [Link](query)
print(f"IP address for domain '{query}': {ip_address}")
except [Link]:
print(f"Unable to resolve '{query}'")
# Driver code
if __name__ == "__main__":
query = input("Enter an IP address or domain name: ").strip()
dns_lookup(query)