Coding Challlenge
Coding Challlenge
Code:
def manchester_encode(binary_string):
encoded = ''
if bit == '1':
encoded += '01'
encoded += '10'
else:
raise ValueError("Input must be a binary string containing only '0' and '1'.")
return encoded
encoded_output = manchester_encode(binary_input)
Output:
Q2. In data communication, Byte Stuffing is a technique used to ensure that special control characters (like flag
or escape characters) are not misinterpreted as data delimiters. In this method: A special character, ESC
(Escape), is used to indicate that the following byte is stuffed (i.e., it is part of data and not a control character).
If the FLAG or ESC appears in the data, it is stuffed by adding an ESC before it. Assume: FLAG = ""F"" ESC = ""E""
You are to write a program that performs Byte Stuffing on a given input data string
Code:
def byte_stuffing(data):
FLAG = "F"
ESC = "E"
stuffed_data = ""
stuffed_data += ESC
stuffed_data += char
return stuffed_data
stuffed_output = byte_stuffing(input_data)
Output:
Q3. The Cyclic Redundancy Check (CRC) is an error-detecting technique used in digital networks and storage
devices to detect accidental changes in raw data. It involves using a generator polynomial (divisor) to compute
a remainder (CRC bits), which is appended to the original data before transmission. Your task is to write a
program that performs the CRC encoding process.
Code:
result = []
return ''.join(result)
n = len(generator)
temp = appended_data[:n]
if temp[0] == '1':
else:
if temp[0] == '1':
else:
crc = temp
return transmitted_data
data_input = input("Enter the binary data: ")
Output:
Q4. You are required to simulate the working of the Carrier Sense Multiple Access (CSMA) protocol. In CSMA,
before a node transmits data, it first senses the channel. If the channel is idle (0), the node starts transmitting
the frame. If the channel is busy (1), the node waits for a random backoff time before trying again. To better
understand real-world transmission delays, use Python's time.sleep() function to simulate: Transmission time
(2 seconds) when the channel is idle. Backoff time (random delay between 1 to 3 seconds) when the channel is
busy
Code:
import time
import random
def csma_simulation():
if channel_status == 0:
print("Transmission successful.")
else:
backoff_time = random.randint(1, 3)
time.sleep(backoff_time)
print("Retrying transmission...")
csma_simulation()
csma_simulation()
Output:
Channel Status: Busy (1)
Retrying transmission...
Transmission successful.
Q5. Write a Python program that takes a domain name as input (e.g., google.com) and returns its
corresponding IP address using the socket library
Code:
import socket
def get_ip_address(domain_name):
try:
ip_address = socket.gethostbyname(domain_name)
return ip_address
except socket.gaierror:
ip = get_ip_address(domain)
Output:
Q6. Write a Python script using the Scapy library to simulate a TCP 3-way handshake between a client and
server. The script should: Send a SYN packet to a target IP and port Receive the SYN-ACK response Complete
the handshake by sending an ACK packet
Code:
ip = IP(dst=target_ip)
if syn_ack is None:
return
send(ip/ack)
else:
tcp_handshake(target_ip, target_port)
output:
Q7. Write a program to simulate CSMA/CD (Carrier Sense Multiple Access with Collision Detection), where:
a)Multiple stations attempt to transmit data over a shared channel. b) If a collision occurs, they wait for a
random backoff time before retransmitting. c) Print the transmission attempts and collision occurrences
Code:
import random
import time
def csma_cd_simulation(num_stations):
max_attempts = 5
transmitting_stations = []
for i in range(num_stations):
if not transmission_success[i]:
transmitting_stations.append(i)
if len(transmitting_stations) > 1:
print(f"\n[Collision] Stations {transmitting_stations} are transmitting at the same time!")
backoff = random.randint(1, 3)
time.sleep(backoff)
attempts[station] += 1
transmission_success[station] = True
elif len(transmitting_stations) == 1:
station = transmitting_stations[0]
time.sleep(2)
transmission_success[station] = True
else:
break
csma_cd_simulation(num_stations)
Output:
Q9. Write a C program that simulates an Ethernet network using CSMA/CD, where: a) Devices attempt to send
frames over a shared medium. b) If two devices transmit at the same time, a collision occurs. c) The program
implements an exponential backoff algorithm to resolve collisions
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define MAX_DEVICES 5
#define MAX_ATTEMPTS 10
sleep(backoff_time);
int main() {
int devices[MAX_DEVICES];
int attempts[MAX_DEVICES];
int transmitted[MAX_DEVICES];
int all_transmitted = 0;
int i, colliding_devices;
srand(time(NULL));
devices[i] = 1;
attempts[i] = 0;
transmitted[i] = 0;
while (!all_transmitted) {
colliding_devices = 0;
colliding_devices++;
if (colliding_devices > 1) {
attempts[i]++;
devices[i] = 0;
} else {
exponential_backoff(attempts[i]);
} else if (colliding_devices == 1) {
transmitted[i] = 1;
devices[i] = 0;
break;
} else {
all_transmitted = 1;
all_transmitted = 0;
break;
return 0;
Output:
Q9. Write a program to simulate SCTP multihoming, where: a) A client has two IP addresses. I) f one
connection fails, SCTP should switch to the alternate IP. c) Demonstrate failover by manually disabling one
connection during transmission
Code:
import socket
import time
import random
port = 9000
try:
sock.connect((server_ip, port))
sock.sendall(message.encode())
sock.close()
return True
except Exception as e:
return False
def sctp_multihoming_simulation():
while True:
if not success:
if not success:
break
else:
print("Transmission successful!")
break
if __name__ == "__main__":
sctp_multihoming_simulation()
Output:
Q10. Write a program to implement Huffman encoding for a given input string. a)Compute character
frequencies. b) Construct the Huffman Tree. c) Generate Huffman Codes and encode the input string. d) Output
the encoded binary string and the Huffman codes
Code:
import heapq
class Node:
self.char = char
self.freq = freq
self.left = None
self.right = None
def build_huffman_tree(freq_map):
heapq.heapify(heap)
left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged.left = left
merged.right = right
heapq.heappush(heap, merged)
return heap[0]
if node is None:
return
code_map[node.char] = prefix
def huffman_encoding(input_string):
if not input_string:
return "", {}
freq_map = Counter(input_string)
root = build_huffman_tree(freq_map)
huffman_codes = generate_codes(root)
if __name__ == "__main__":
print("\nHuffman Codes:")
print(f"'{char}': {code}")
print(f"\nEncoded String:\n{encoded_string}")
Output:
Huffman Codes:
'A': 0
'B': 111
'R': 110
'C': 101
'D': 100
Encoded String:
01111100100001111110110