[go: up one dir, main page]

0% found this document useful (0 votes)
19 views45 pages

Cn Practicals

The document outlines various experiments related to networking, including the implementation of different topologies using Packet Tracer, configuring router networks with RIP, subnetting calculations, and socket programming in Java for both UDP and TCP protocols. It also covers file transfer methods using HTTP, HTTPS, FTP, and UDP sockets, with detailed code examples for server and client implementations. Each experiment demonstrates practical applications of networking concepts and programming techniques.

Uploaded by

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

Cn Practicals

The document outlines various experiments related to networking, including the implementation of different topologies using Packet Tracer, configuring router networks with RIP, subnetting calculations, and socket programming in Java for both UDP and TCP protocols. It also covers file transfer methods using HTTP, HTTPS, FTP, and UDP sockets, with detailed code examples for server and client implementations. Each experiment demonstrates practical applications of networking concepts and programming techniques.

Uploaded by

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

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: {network.netmask}")
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 network.subnets():
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., 192.168.1.0/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 java.net.DatagramPacket;

import java.net.DatagramSocket;

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, buffer.length);

socket.receive(packet);

String message = new String(packet.getData(), 0, packet.getLength());

System.out.println("Client: " + message);

String response = "Message received";

socket.send(new DatagramPacket(response.getBytes(), response.length(),


packet.getAddress(), packet.getPort()));

}
import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPClient {

public static void main(String[] args) throws Exception {

DatagramSocket socket = new DatagramSocket();

String message = "Hello from client";

InetAddress serverAddress = InetAddress.getByName("localhost");

socket.send(new DatagramPacket(message.getBytes(), message.length(), serverAddress, 8080));

System.out.println("Message sent: " + message);

byte[] buffer = new byte[1024];

DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);

socket.receive(responsePacket);

System.out.println("Server: " + new String(responsePacket.getData(), 0,


responsePacket.getLength()));

}
import java.io.*;

import java.net.*;

public class TCPServer {

public static void main(String[] args) throws Exception {

ServerSocket serverSocket = new ServerSocket(8080);

System.out.println("TCP server listening on port 8080");

while (true) {

Socket clientSocket = serverSocket.accept();

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

String message = in.readLine();

System.out.println("Client: " + message);

out.println("Message received");

clientSocket.close();

}
}

import java.io.*;

import java.net.*;

public class TCPClient {

public static void main(String[] args) throws Exception {

Socket socket = new Socket("localhost", 8080);

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String message = "Hello from client";

out.println(message);

System.out.println("Message sent: " + message);

System.out.println("Server: " + in.readLine());

socket.close();

}
Exp 6.
TCP socket for wired network
a. Say Hello to each other
b.File Transfer

a.Server.py

import socket

import os

HOST = '0.0.0.0' # 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 os.path.basename(filename)
def start_server():

with socket.socket(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 = conn.recv(1024).decode()

print(f"Client: {greeting}")

# Send a greeting back to the client

conn.sendall(b'Hello from Server')

# Receive the filename from client and sanitize it

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

filename = sanitize_filename(filename)

print(f"Receiving file: {filename}")

# Send readiness acknowledgment

conn.sendall(b'READY')

# Create folder for received files if it doesn't exist

save_path = os.path.join("received_files", filename)

os.makedirs("received_files", exist_ok=True)

# Start receiving file data in chunks


with open(save_path, 'wb') as f:

while True:

chunk = conn.recv(1024)

if not chunk: # Exit if no more data

break

f.write(chunk)

print(f"File '{filename}' received and saved successfully.")

if __name__ == "__main__":

start_server()
a. Client.py

import socket

import os

HOST = '192.168.43.219'

PORT = 65433

def start_client():

filename = r"D:\CN Practicals\practical 6\example.txt" # File to be sent

# Check if the file exists

if not os.path.exists(filename):

print(f"Error: '{filename}' not found.")

return

with socket.socket(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(os.path.basename(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 := f.read(1024):

client_socket.sendall(chunk)

print("File sent successfully.")

except socket.error 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 = '127.0.0.1'

SERVER_PORT = 12345

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

print(f'Starting server on {SERVER_IP}:{SERVER_PORT}')

# Bind and listen for incoming connections

sock.bind((SERVER_IP, SERVER_PORT))

sock.listen(1)

while True:

print('Waiting for a connection...')

connection, client_addr = sock.accept()


try:

print(f"Connected by {client_addr}")

start = time.time() # Start time tracking for file upload

# Receive the filename from the client

file_name = connection.recv(BUFFER_FILENAME).decode()

file_name = os.path.basename(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 := fd.read(BUFFER_SIZE)):

connection.send(buf)

except FileNotFoundError:

print(f"Error: File '{file_name}' not found.")

connection.send(b"ERROR: File not found.") # Send error to client if file is missing

continue

end = time.time() # 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

connection.close()
b. tcp_client1.py

import socket

import os

import time

BUFFER_SIZE = 32

HOST = '127.0.0.1'

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 Shrugged.txt"

elif file_number == 2:

file_name = "Don Quixote.txt"

elif file_number == 3:

file_name = "Shogun.txt"

elif file_number == 4:

file_name = "The Stand.txt"

elif file_number == 5:

file_name = "War and Peace.txt"

else:

print("Invalid selection.")

exit()

# Prepare the socket connection

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

try:

print('Connecting to', HOST)

sock.connect((HOST, PORT))

print('Connected')

# Send filename to the server

sock.send(file_name.encode())
# Construct the new filename

base_name, extension = os.path.splitext(file_name)

new_file_name = f"{base_name}+Protocol=TCP+{os.getpid()}{extension}"

# Start time tracking

start = time.time()

# 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 = sock.recv(BUFFER_SIZE)

if not byte: # Break if no more data is received

break

f.write(byte) # Write received data to file

end = time.time() # End time tracking

# Calculate the file size and throughput

file_size = os.stat(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:

sock.close() # 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 pc1.txt created on PC1 to the server.

Upload the file pc2.txt created on PC2 to the server.


Download the file pc2.txt shared by PC2 onto PC1
Download the file pc1.txt 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 = '127.0.0.1'

SERVER_PORT = 12345

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print('Starting server on port', SERVER_PORT)

sock.bind((SERVER_IP, SERVER_PORT))

while True:

print('Waiting to receive message')

# Receive the filename from the client

file_name, client_addr = sock.recvfrom(BUFFER_FILENAME)

print(client_addr, 'connected')
start = time.time()

# Decode and prepare the file name

file_name = file_name.decode().strip()

file_name = os.path.basename(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 = fd.read(BUFFER_SIZE)

while buf:

sock.sendto(buf, client_addr)

buf = fd.read(BUFFER_SIZE)

end = time.time()

print(f"Time taken to upload: {end - start} sec")

print(file_name, "uploaded successfully")

except FileNotFoundError:

print(f"File {file_name} not found.")

sock.close()
UDP_client.py

import socket

import os

import time

BUFFER_SIZE = 32

HOST = '127.0.0.1'

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 Shrugged.txt"

elif file_number == 2:
file_name = "Don Quixote.txt"

elif file_number == 3:

file_name = "Shogun.txt"

elif file_number == 4:

file_name = "The Stand.txt"

elif file_number == 5:

file_name = "War and Peace.txt"

else:

print("Invalid selection.")

exit()

file = file_name.split('.')

# Set up UDP socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

try:

start = time.time()

# Send file name to server

sock.sendto(file_name.encode(), server_addr)

# Create unique file name for the received file

file_name = file[0] + "+Protocol=UDP" + "+" + str(os.getpid()) + "." + file[1]

with open(file_name, 'wb') as f:

print('Receiving Data')

while True:

sock.settimeout(2) # Set a timeout for receiving data

try:
byte, server = sock.recvfrom(BUFFER_SIZE)

if not byte:

break # End if no data received

f.write(byte) # Write data to file

except socket.timeout:

print("Timeout Occurred")

break

end = time.time()

print(f"Time taken to download: {end - start} sec")

print("Downloaded", file_name)

# Calculate throughput

file_stat = os.stat(file_name)

file_size = file_stat.st_size

throughput = round((file_size * 0.001) / (end - start), 3)

print("Throughput:", throughput, "kB/s")

finally:

sock.close()
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 – 10.0.0.2 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 = socket.gethostbyaddr(query)

print(f"Domain name for IP '{query}': {host[0]}")

except socket.error:

# If it's not a valid IP, assume it's a domain and perform DNS lookup

try:

ip_address = socket.gethostbyname(query)

print(f"IP address for domain '{query}': {ip_address}")

except socket.gaierror:

print(f"Unable to resolve '{query}'")

# Driver code

if __name__ == "__main__":

query = input("Enter an IP address or domain name: ").strip()

dns_lookup(query)

You might also like