Added codes.
This commit is contained in:
parent
550e7b68ed
commit
a4b26b60a4
102
Codes/Code-A3 (CRC).cpp
Normal file
102
Codes/Code-A3 (CRC).cpp
Normal file
@ -0,0 +1,102 @@
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
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<keyLen; i++) {
|
||||
if (i < dataLen) {
|
||||
// Only perform XOR if within the length of data
|
||||
if (data[i] == key[i]) {
|
||||
result += '0';
|
||||
}
|
||||
else {
|
||||
result += '1';
|
||||
}
|
||||
} else {
|
||||
// If data length exceeded, append the key
|
||||
result += key[i];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
string encoder(string data, string key) {
|
||||
int keyLen = key.length();
|
||||
|
||||
// Append n-1 zeroes to the data
|
||||
string dataWithZeroes = data + string(keyLen-1, '0');
|
||||
|
||||
// Perform XOR operation with the key
|
||||
string remainder = XOR(dataWithZeroes, key);
|
||||
|
||||
// Get the remainder (last n-1 bits)
|
||||
string crc = remainder.substr(remainder.length() - (keyLen-1));
|
||||
|
||||
// Append the CRC to the original data
|
||||
return data + crc;
|
||||
}
|
||||
|
||||
string performDivision(string data, string key) {
|
||||
int keyLen = key.length();
|
||||
|
||||
// Initialize with the data to be divided
|
||||
string temp = data.substr(0, keyLen);
|
||||
|
||||
// Perform XOR operations on each segment
|
||||
for (int i = keyLen; i < data.length(); i++) {
|
||||
if (temp[0] == '1') { // Only perform XOR if the leading bit is 1
|
||||
temp = XOR(temp, key);
|
||||
}
|
||||
temp = temp.substr(1) + data[i]; // Shift left and add the next bit
|
||||
}
|
||||
|
||||
// Perform the final XOR operation
|
||||
if (temp[0] == '1') {
|
||||
temp = XOR(temp, key);
|
||||
}
|
||||
|
||||
// Extract the remainder (last keyLen-1 bits)
|
||||
return temp.substr(temp.length() - (keyLen - 1));
|
||||
}
|
||||
|
||||
// Function to check the correctness of received data
|
||||
bool checkData(string data, string key) {
|
||||
string remainder = performDivision(data, key);
|
||||
return (remainder.find('1') == string::npos); // No '1' means remainder is all zeros
|
||||
}
|
||||
|
||||
int main() {
|
||||
string data, key;
|
||||
|
||||
cout << endl << "Enter data:\t";
|
||||
getline(cin, data);
|
||||
cout << "Enter primary key:\t";
|
||||
getline(cin, key);
|
||||
|
||||
cout<<endl<<"Original data:\t"<<data;
|
||||
cout<<endl<<"Key:\t"<<key;
|
||||
string messageToSend = encoder(data, key);
|
||||
cout<<endl<<"----------------------------------------"<<endl;
|
||||
cout<<"Message to be sent:\t"<<messageToSend;
|
||||
cout<<endl<<"----------------------------------------"<<endl;
|
||||
|
||||
string receivedData;
|
||||
cout<<endl<<"HINT: Received data should be the same as message to be sent.";
|
||||
cout<<endl<<"Enter received data:\t";
|
||||
getline(cin, receivedData);
|
||||
|
||||
if (receivedData == messageToSend) {
|
||||
cout<<"The received data is correct."<<endl;
|
||||
} else {
|
||||
cout<<"The received data appears to be tampered."<<endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
103
Codes/Code-A3 (Hamming Code).cpp
Normal file
103
Codes/Code-A3 (Hamming Code).cpp
Normal file
@ -0,0 +1,103 @@
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
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<int> encodeData(vector<int> data) {
|
||||
int dataBits = data.size();
|
||||
int parityBits = calculateParityBits(dataBits);
|
||||
vector<int> 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<int> 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<int> data(dataBits);
|
||||
cout<<endl<<"NOTE: Make sure the bits are entered in binary format, separated by spaces.\nEg. 1 0 0 1 (for 4 data bits).";
|
||||
cout<<endl<<"Enter the data bits:\t";
|
||||
for (int i = 0; i < dataBits; i++) {
|
||||
cin >> data[i];
|
||||
}
|
||||
|
||||
vector<int> encoded = encodeData(data);
|
||||
cout<<endl<<"--------------------"<<endl;
|
||||
cout<<"Encoded bits are:\t";
|
||||
for (int bit : encoded) {
|
||||
cout << bit << " ";
|
||||
}
|
||||
cout<<endl<<"--------------------"<<endl;
|
||||
|
||||
cout<<endl<<"Enter the encoded bits:\t";
|
||||
vector<int> 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."<<endl;
|
||||
} else {
|
||||
cout<<"Error detected at position: "<<errorPosition<<endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
78
Codes/Code-A4 (Sliding Window).cpp
Normal file
78
Codes/Code-A4 (Sliding Window).cpp
Normal file
@ -0,0 +1,78 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <queue>
|
||||
using namespace std;
|
||||
|
||||
class SlidingWindow {
|
||||
private:
|
||||
int window_size;
|
||||
int total_frames;
|
||||
vector<int> 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 "<<sent_frames.back()<<endl;
|
||||
}
|
||||
else {
|
||||
cout<<"Window is full. Waiting before sending next frames."<<endl;
|
||||
}
|
||||
}
|
||||
|
||||
// receive a frame
|
||||
void receive_frame(int frame_number) {
|
||||
if (frame_number == next_frame_to_receive) {
|
||||
next_frame_to_receive++;
|
||||
cout<<"Received frame "<<frame_number<<endl;
|
||||
}
|
||||
else {
|
||||
cout<<"Received frame "<<frame_number<<", but expected frame "<<next_frame_to_receive<<endl;
|
||||
}
|
||||
// remove acknowledged frames from the sent_frames queue
|
||||
while (!sent_frames.empty() && sent_frames.front()<=next_frame_to_receive-1) {
|
||||
sent_frames.erase(sent_frames.begin());
|
||||
}
|
||||
}
|
||||
|
||||
bool all_frames_sent() {
|
||||
return next_frame_to_send == total_frames;
|
||||
}
|
||||
|
||||
bool all_frames_received() {
|
||||
return next_frame_to_receive == total_frames;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
int window_size, total_frames;
|
||||
cout << "Enter the window size:\t";
|
||||
cin >> 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<rand()%3; i++) {
|
||||
int frame_number = rand() % total_frames;
|
||||
window.receive_frame(frame_number);
|
||||
}
|
||||
}
|
||||
cout<<"All frames sent and received successfully!"<<endl;
|
||||
|
||||
return 0;
|
||||
}
|
35
Codes/Code-B5.cpp
Normal file
35
Codes/Code-B5.cpp
Normal file
@ -0,0 +1,35 @@
|
||||
#include <iostream>
|
||||
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
|
||||
*/
|
98
Codes/Code-B6.py
Normal file
98
Codes/Code-B6.py
Normal file
@ -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')
|
56
Codes/Code-B8 (Client).py
Executable file
56
Codes/Code-B8 (Client).py
Executable file
@ -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()
|
90
Codes/Code-B8 (Server).py
Executable file
90
Codes/Code-B8 (Server).py
Executable file
@ -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()
|
||||
|
28
Codes/Code-B9 (Receiver).py
Normal file
28
Codes/Code-B9 (Receiver).py
Normal file
@ -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)
|
30
Codes/Code-B9 (Sender).py
Normal file
30
Codes/Code-B9 (Sender).py
Normal file
@ -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)
|
26
Codes/Code-C10.py
Normal file
26
Codes/Code-C10.py
Normal file
@ -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()
|
34
Codes/Code-C11.py
Normal file
34
Codes/Code-C11.py
Normal file
@ -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)
|
34
README.md
34
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
|
||||
|
||||
<details open>
|
||||
<summary>1. Code-A3</summary>
|
||||
<ul>
|
||||
<li><a href="https://git.kska.io/sppu-te-comp-content/ComputerNetworksAndSecurity/src/branch/main/Codes/Code-A3%20%28CRC%29.cpp">CRC</a></li>
|
||||
<li><a href="https://git.kska.io/sppu-te-comp-content/ComputerNetworksAndSecurity/src/branch/main/Codes/Code-A3%20%28Hamming%20Code%29.cpp">Hamming Code</a></li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
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)
|
||||
|
||||
<details open>
|
||||
<summary>5. Code-B8</summary>
|
||||
<ul>
|
||||
<li><a href="https://git.kska.io/sppu-te-comp-content/ComputerNetworksAndSecurity/src/branch/main/Codes/Code-B8%20%28Client%29.py">Client</a></li>
|
||||
<li><a href="https://git.kska.io/sppu-te-comp-content/ComputerNetworksAndSecurity/src/branch/main/Codes/Code-B8%20%28Server%29.py">Server</a></li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details open>
|
||||
<summary>6. Code-B9</summary>
|
||||
<ul>
|
||||
<li><a href="https://git.kska.io/sppu-te-comp-content/ComputerNetworksAndSecurity/src/branch/main/Codes/Code-B9%20%28Receiver%29.py">Receiver</a></li>
|
||||
<li><a href="https://git.kska.io/sppu-te-comp-content/ComputerNetworksAndSecurity/src/branch/main/Codes/Code-B9%20%28Sender%29.py">Sender</a></li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
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).
|
||||
|
Loading…
Reference in New Issue
Block a user