diff --git a/Codes/Code-A3 (CRC).cpp b/Codes/Code-A3 (CRC).cpp new file mode 100644 index 0000000..c8bb556 --- /dev/null +++ b/Codes/Code-A3 (CRC).cpp @@ -0,0 +1,102 @@ +#include +#include +using namespace std; + +string XOR(string data, string key) { + // Dividend is data + // Divisor is the primary key, i.e. the key + string result = ""; + int dataLen = data.length(); + int keyLen = key.length(); + + // Perform XOR operation + for (int i=0; i +#include +#include +using namespace std; + +// Function to calculate the number of parity bits needed +int calculateParityBits(int dataBits) { + int parityBits = 0; + while (pow(2, parityBits) < dataBits + parityBits + 1) { + parityBits++; + } + return parityBits; +} + +// Function to encode the data using Hamming code +vector encodeData(vector data) { + int dataBits = data.size(); + int parityBits = calculateParityBits(dataBits); + vector encoded(dataBits + parityBits, 0); + + // Set the data bits + int j = 0; + for (int i = 0; i < encoded.size(); i++) { + if (i + 1 == pow(2, j)) { + j++; + } else { + encoded[i] = data[i - j]; + } + } + + // Calculate and set the parity bits + for (int i = 0; i < parityBits; i++) { + int parityBit = pow(2, i); + int sum = 0; + for (int j = parityBit - 1; j < encoded.size(); j += 2 * parityBit) { + for (int k = 0; k < parityBit; k++) { + if (j + k < encoded.size()) { + sum += encoded[j + k]; + } + } + } + encoded[parityBit - 1] = sum % 2; + } + + return encoded; +} + +// Function to check for errors in the encoded data +int checkForErrors(vector encoded) { + int parityBits = calculateParityBits(encoded.size() - calculateParityBits(encoded.size())); + int errorPosition = 0; + + for (int i = 0; i < parityBits; i++) { + int parityBit = pow(2, i); + int sum = 0; + for (int j = parityBit - 1; j < encoded.size(); j += 2 * parityBit) { + for (int k = 0; k < parityBit; k++) { + if (j + k < encoded.size()) { + sum += encoded[j + k]; + } + } + } + errorPosition += (sum % 2) * parityBit; + } + + return errorPosition; +} + +int main() { + int dataBits; + cout<<"Enter the number of data bits:\t"; + cin >> dataBits; + + vector data(dataBits); + cout<> data[i]; + } + + vector encoded = encodeData(data); + cout< receivedEncoded(encoded.size()); + for (int i = 0; i < encoded.size(); i++) { + cin >> receivedEncoded[i]; + } + + int errorPosition = checkForErrors(receivedEncoded); + if (errorPosition == 0) { + cout<<"No errors detected."< +#include +#include +using namespace std; + +class SlidingWindow { +private: + int window_size; + int total_frames; + vector sent_frames; // queue of sent frames + int next_frame_to_send; // index of the next frame to send + int next_frame_to_receive; // index of the next frame to receive + +public: + SlidingWindow(int window_size, int total_frames) { + this->window_size = window_size; + this->total_frames = total_frames; + this->next_frame_to_send = 0; + this->next_frame_to_receive = 0; + } + + // send a frame + void send_frame() { + if (sent_frames.size() < window_size && next_frame_to_send < total_frames) { + sent_frames.push_back(next_frame_to_send); + next_frame_to_send++; + cout<<"Sent frame "<> window_size; + cout << "Enter the total number of frames:\t"; + cin >> total_frames; + + SlidingWindow window(window_size, total_frames); + + while (!window.all_frames_sent() || !window.all_frames_received()) { + window.send_frame(); + // simulate receiving frames + for (int i=0; i +using namespace std; + +void printSubnetMask(int prefixLength) { + int mask[4] = {0, 0, 0, 0}; + for (int i = 0; i < prefixLength; ++i) { + mask[i / 8] |= (1 << (7 - (i % 8))); + } + cout << "Subnet Mask for /" << prefixLength << ": "; + cout << mask[0] << "." << mask[1] << "." << mask[2] << "." << mask[3] << std::endl; +} + +int main() { + int prefixLength; + cout << "Enter the prefix length: "; + cin >> prefixLength; + + if (prefixLength >= 0 && prefixLength <= 32) { + printSubnetMask(prefixLength); + } + else { + cout << "Invalid prefix length!" << std::endl; + } + return 0; +} + +/* +OUTPUT: +Enter the prefix length: 22 +Subnet Mask for /22: 255.255.252.0 +Enter the prefix length: 0 +Subnet Mask for /0: 0.0.0.0 +Enter the prefix length: 32 +Subnet Mask for /32: 255.255.255.255 +*/ diff --git a/Codes/Code-B6.py b/Codes/Code-B6.py new file mode 100644 index 0000000..da3bd87 --- /dev/null +++ b/Codes/Code-B6.py @@ -0,0 +1,98 @@ +import heapq + +class LinkStateNetwork: + def __init__(self): + self.graph = {} + + def add_edge(self, src, dest, weight): + if src not in self.graph: + self.graph[src] = {} + if dest not in self.graph: + self.graph[dest] = {} + self.graph[src][dest] = weight + self.graph[dest][src] = weight # Undirected graph + + def dijkstra(self, start): + distances = {node: float('inf') for node in self.graph} + distances[start] = 0 + priority_queue = [(0, start)] + shortest_paths = {node: [] for node in self.graph} + + while priority_queue: + current_distance, current_node = heapq.heappop(priority_queue) + if current_distance > distances[current_node]: + continue + for neighbor, weight in self.graph[current_node].items(): + distance = current_distance + weight + if distance < distances[neighbor]: + distances[neighbor] = distance + shortest_paths[neighbor] = shortest_paths[current_node] + [current_node] + heapq.heappush(priority_queue, (distance, neighbor)) + return distances, shortest_paths + + def print_routing_table(self, start): + distances, paths = self.dijkstra(start) + print(f"Link-State Routing Table from {start}:") + for destination in distances: + if distances[destination] < float('inf'): + print(f"To {destination} via {' -> '.join(paths[destination] + [destination])}, cost: {distances[destination]}") + else: + print(f"To {destination}: Unreachable") + +# Example usage of Link-State +if __name__ == "__main__": + link_state_network = LinkStateNetwork() + link_state_network.add_edge('A', 'B', 1) + link_state_network.add_edge('A', 'C', 4) + link_state_network.add_edge('B', 'C', 2) + link_state_network.add_edge('B', 'D', 5) + link_state_network.add_edge('C', 'D', 1) + link_state_network.print_routing_table('A') + +class DistanceVectorNetwork: + def __init__(self): + self.graph = {} + self.distance_table = {} + + def add_edge(self, src, dest, weight): + if src not in self.graph: + self.graph[src] = {} + if dest not in self.graph: + self.graph[dest] = {} + self.graph[src][dest] = weight + self.graph[dest][src] = weight # Undirected graph + + def initialize_distance_table(self, start): + for node in self.graph: + self.distance_table[node] = {n: float('inf') for n in self.graph} + self.distance_table[start][start] = 0 + for neighbor in self.graph[start]: + self.distance_table[start][neighbor] = self.graph[start][neighbor] + + def update_distance_table(self): + for _ in range(len(self.graph) - 1): + for src in self.graph: + for dest in self.graph[src]: + for neighbor in self.graph[src]: + if self.distance_table[src][dest] > self.distance_table[src][neighbor] + self.distance_table[neighbor][dest]: + self.distance_table[src][dest] = self.distance_table[src][neighbor] + self.distance_table[neighbor][dest] + + def print_routing_table(self, start): + self.initialize_distance_table(start) + self.update_distance_table() + print(f"Distance Vector Routing Table from {start}:") + for destination in self.distance_table[start]: + if self.distance_table[start][destination] < float('inf'): + print(f"To {destination}: Cost: {self.distance_table[start][destination]}") + else: + print(f"To {destination}: Unreachable") + +# Example usage of Distance Vector +if __name__ == "__main__": + distance_vector_network = DistanceVectorNetwork() + distance_vector_network.add_edge('A', 'B', 1) + distance_vector_network.add_edge('A', 'C', 4) + distance_vector_network.add_edge('B', 'C', 2) + distance_vector_network.add_edge('B', 'D', 5) + distance_vector_network.add_edge('C', 'D', 1) + distance_vector_network.print_routing_table('A') diff --git a/Codes/Code-B8 (Client).py b/Codes/Code-B8 (Client).py new file mode 100755 index 0000000..5f9b934 --- /dev/null +++ b/Codes/Code-B8 (Client).py @@ -0,0 +1,56 @@ +# TCP (lan) based chatting app + +# -------------------------------------------------------------- +# client.py +# -------------------------------------------------------------- + +# req. libs +import socket +import threading + + +# global +## connection data +host = '127.0.0.1' # server ip +port = 4444 # free/open port +print(f"[#] connecting to {host}:{port}") + +## nickname +nickname = input("[+] enter nickname:") + +## starting client +client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +client.connect((host, port)) +print(f"[+] connected to {host}:{port}") + + +# listening to server & sending nickname +def receive(): + while True: + try: + # receive msg + msg = client.recv(1024).decode('ascii') + + # print msg + if msg == 'NICKNAME': + client.send(nickname.encode('ascii')) + else: + print(msg) + except: + print("[!] error 404\n[#] terminating...") + client.close() + break + +# send msg to server +def write(): + while True: + msg = f"{nickname}: {input('')}" + client.send(msg.encode('ascii')) + + +# starting threads for listening & writing +receive_thread = threading.Thread(target=receive) +receive_thread.start() + +write_thread = threading.Thread(target=write) +write_thread.start() diff --git a/Codes/Code-B8 (Server).py b/Codes/Code-B8 (Server).py new file mode 100755 index 0000000..e2a80fc --- /dev/null +++ b/Codes/Code-B8 (Server).py @@ -0,0 +1,90 @@ +# TCP (lan) based chatting app + +# -------------------------------------------------------------- +# server.py +# -------------------------------------------------------------- + + +# req. libs +import socket +import threading + + + +# global +## connection data +host = '127.0.0.1' # server ip +port = 4444 # free/open port + +## starting server +server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # AF_INET - using internal socket, rather than unix socket + # SOCK_STREAM - using tcp (& not udp) +server.bind((host,port)) +server.listen() + +## clients & nicknames +clients = [] +nicknames = [] + +print(f"[+] Server is running on {host}:{port}") + + +# send msg to all clients +def broadcast(msg): + for client in clients: + client.send(msg) + + +# handling clients +def handle(client): + while True: + try: + msg = client.recv(1024) + broadcast(msg) + except: + # disconnecting inactive clients + index = clients.index(client) + + # del f/ clients + try: clients.remove(index) + except: pass + client.close() + + # del f/ nicknames + nickname = nicknames.index(index) + nicknames.remove(nickname) + + # display + print(f"[-] '{nickname}' left") + break + + +# listening +def receive(): + while True: + # accept conn + client, addr = server.accept() + print(f"[+] '{str(addr)}' connected") + + # request & store nickname + client.send('NICKNAME'.encode('ascii')) + nickname = client.recv(1024).decode('ascii') + + # store + clients.append(client) + nicknames.append(nickname) + + # display + print(f"[+] '{nickname}' connected") + + # send msg + broadcast(f"[#] {nickname} connected to the server\n".encode('ascii')) + + # handle + client_handler = threading.Thread(target=handle, args=(client,)) + client_handler.start() + + +receive() + diff --git a/Codes/Code-B9 (Receiver).py b/Codes/Code-B9 (Receiver).py new file mode 100644 index 0000000..9b339d4 --- /dev/null +++ b/Codes/Code-B9 (Receiver).py @@ -0,0 +1,28 @@ +import socket + +def receive_file(port): + # Create a UDP socket + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(('', port)) + print(f"Listening for incoming files on port {port}...") + + # Receive file information + data, addr = sock.recvfrom(1024) + filename, filesize = data.decode().split(":") + filesize = int(filesize) + + with open(filename, "wb") as f: + print(f"Receiving {filename}...") + bytes_received = 0 + + while bytes_received < filesize: + data, addr = sock.recvfrom(1024) # Receive in chunks + f.write(data) + bytes_received += len(data) + + print(f"File {filename} received successfully.") + sock.close() + +if __name__ == "__main__": + port = int(input("Enter the port to listen on: ")) + receive_file(port) diff --git a/Codes/Code-B9 (Sender).py b/Codes/Code-B9 (Sender).py new file mode 100644 index 0000000..1355bbd --- /dev/null +++ b/Codes/Code-B9 (Sender).py @@ -0,0 +1,30 @@ +import socket +import os + +def send_file(filename, host, port): + # Create a UDP socket + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + + # Get file size + filesize = os.path.getsize(filename) + sock.sendto(f"{filename}:{filesize}".encode(), (host, port)) + + with open(filename, "rb") as f: + print(f"Sending {filename}...") + bytes_sent = 0 + + while bytes_sent < filesize: + data = f.read(1024) # Read in chunks + sock.sendto(data, (host, port)) + bytes_sent += len(data) + + print(f"File {filename} sent successfully.") + sock.close() + +if __name__ == "__main__": + target_host = input("Enter the receiver's IP address: ") + target_port = int(input("Enter the receiver's port: ")) + + # Choose a file to send + filename = input("Enter the file path to send (Text, Audio, Video, or Script): ") + send_file(filename, target_host, target_port) diff --git a/Codes/Code-C10.py b/Codes/Code-C10.py new file mode 100644 index 0000000..db80765 --- /dev/null +++ b/Codes/Code-C10.py @@ -0,0 +1,26 @@ +import socket + +def dns_lookup(): + choice = input("Choose an operation:\n1 -> lookup a URL\n2 -> lookup an IP address\nEnter choice (1/2):\t") + + if choice == '1': + url = input("Enter the URL (e.g. kska.io): ") + try: + ip_address = socket.gethostbyname(url) + print(f"The IP address for {url} is: {ip_address}") + except socket.gaierror: + print("Error: Unable to resolve the URL.") + + elif choice == '2': + ip_address = input("Enter the IP address (e.g. 93.184.216.34): ") + try: + url = socket.gethostbyaddr(ip_address)[0] + print(f"The URL for {ip_address} is: {url}") + except socket.herror: + print("Error: Unable to resolve the IP address.") + + else: + print("Invalid choice. Please enter 1 or 2.") + +if __name__ == "__main__": + dns_lookup() diff --git a/Codes/Code-C11.py b/Codes/Code-C11.py new file mode 100644 index 0000000..3a472b4 --- /dev/null +++ b/Codes/Code-C11.py @@ -0,0 +1,34 @@ +import paramiko + +def install_dhcp_server(remote_host, username, password): + # Create an SSH client + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + try: + # Connect to the remote machine + ssh.connect(remote_host, username=username, password=password) + + # Update package list + stdin, stdout, stderr = ssh.exec_command('sudo apt update') + stdout.channel.recv_exit_status() # Wait for the command to complete + + # Install ISC DHCP Server + stdin, stdout, stderr = ssh.exec_command('sudo apt install -y isc-dhcp-server') + stdout.channel.recv_exit_status() # Wait for the command to complete + + # Optional: you can add more commands to configure the DHCP server here + print("DHCP server installed successfully.") + + except Exception as e: + print(f"An error occurred: {e}") + + finally: + # Close the SSH connection + ssh.close() + +if __name__ == "__main__": + remote_host = "192.168.1.100" # Replace with your remote machine's IP + username = "your_username" # Replace with your SSH username + password = "your_password" # Replace with your SSH password + install_dhcp_server(remote_host, username, password) diff --git a/README.md b/README.md index 727094f..6af9923 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,40 @@ This Git repository is a comprehensive resource for the Computer Networks and Se 5. [Unit 5 - Application Layer](Notes/Unit%205%20-%20Application%20Layer) 6. [Unit 6 - Security](Notes/Unit%206%20-%20Security) + +### Codes + +
+ 1. Code-A3 + +
+ +2. [Code-A4 (Sliding Window)](Codes/Code-A4%20%28Sliding%20Window%29.cpp) +3. [Code-B5](Codes/Code-B5.cpp) +4. [Code-B6](Codes/Code-B6.py) + +
+ 5. Code-B8 + +
+ +
+ 6. Code-B9 + +
+ +7. [Code-C10](Codes/Code-C10.py) +8. [Code-C11](Codes/Code-C11.py) + ### Assigments > Each folder contains **handout**, **write-up** and **softcopy** (i.e. code + output).