Coding Challenge
Submitted To: Submitted By:
Dr. Prasenjit Das Mr. Jahir
B.Tech(CSE)
6th Semister
Section: A
ADTU/2022-26/BCS/073
Date: 28th April 2025
Q1. Manchester encoding is a method of encoding digital data where each bit of data is represented by two
level transitions. In IEEE 802.3 (Ethernet) standard, the encoding is as follows: Bit 1 is represented as Low to
High (01) Bit 0 is represented as High to Low (10) Write a program that takes a binary string as input and
returns its Manchester encoded form
Code:
def manchester_encode(binary_string):
encoded = ''
for bit in binary_string:
if bit == '1':
encoded += '01'
elif bit == '0':
encoded += '10'
else:
raise ValueError("Input must be a binary string containing only '0' and '1'.")
return encoded
binary_input = input("Enter a binary string: ")
encoded_output = manchester_encode(binary_input)
print("Manchester Encoded Output:", encoded_output)
Output:
Enter a binary string: 1010
Manchester Encoded Output: 01100110
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 = ""
for char in data:
if char == FLAG or char == ESC:
stuffed_data += ESC
stuffed_data += char
return stuffed_data
input_data = input("Enter the input data string: ")
stuffed_output = byte_stuffing(input_data)
print("Byte Stuffed Output:", stuffed_output)
Output:
Enter the input data string: HEYFLAGESC
Byte Stuffed Output: HEYEFELAGEESC
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:
def xor(a, b):
result = []
for i in range(1, len(b)):
result.append('0' if a[i] == b[i] else '1')
return ''.join(result)
def crc_encode(data, generator):
n = len(generator)
appended_data = data + '0' * (n - 1)
temp = appended_data[:n]
for i in range(n, len(appended_data)):
if temp[0] == '1':
temp = xor(temp, generator) + appended_data[i]
else:
temp = xor(temp, '0' * n) + appended_data[i]
if temp[0] == '1':
temp = xor(temp, generator)
else:
temp = xor(temp, '0' * n)
crc = temp
transmitted_data = data + crc
return transmitted_data
data_input = input("Enter the binary data: ")
generator_input = input("Enter the generator polynomial (binary): ")
encoded_output = crc_encode(data_input, generator_input)
print("CRC Encoded Output:", encoded_output)
Output:
Enter the binary data: 11010011101100
Enter the generator polynomial (binary): 1011
CRC Encoded Output: 11010011101100100
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():
# 0 means idle, 1 means busy
channel_status = random.choice([0, 1])
print(f"Channel Status: {'Idle (0)' if channel_status == 0 else 'Busy (1)'}")
if channel_status == 0:
print("Channel is idle. Starting transmission...")
time.sleep(2) # Simulate 2 seconds of transmission time
print("Transmission successful.")
else:
print("Channel is busy. Waiting for random backoff time...")
backoff_time = random.randint(1, 3)
print(f"Backoff time: {backoff_time} seconds")
time.sleep(backoff_time)
print("Retrying transmission...")
csma_simulation()
csma_simulation()
Output:
Channel Status: Busy (1)
Channel is busy. Waiting for random backoff time...
Backoff time: 3 seconds
Retrying transmission...
Channel Status: Idle (0)
Channel is idle. Starting 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:
return "Invalid domain name or unable to resolve."
domain = input("Enter a domain name (e.g., google.com): ")
ip = get_ip_address(domain)
print(f"The IP address of {domain} is: {ip}")
Output:
Enter a domain name (e.g., google.com): openai.com
The IP address of openai.com is: 104.18.12.123
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:
from scapy.all import IP, TCP, send, sr1
def tcp_handshake(target_ip, target_port):
print("[*] Sending SYN packet...")
ip = IP(dst=target_ip)
syn = TCP(dport=target_port, flags="S", seq=1000)
syn_ack = sr1(ip/syn, timeout=2)
if syn_ack is None:
print("[!] No response received. Host might be down or filtered.")
return
if syn_ack.haslayer(TCP) and syn_ack.getlayer(TCP).flags == 0x12:
print("[*] Received SYN-ACK, sending ACK to complete handshake...")
ack = TCP(dport=target_port, flags="A", seq=syn_ack.ack, ack=syn_ack.seq + 1)
send(ip/ack)
print("[*] Handshake completed successfully.")
else:
print("[!] Unexpected response. TCP Handshake failed.")
target_ip = input("Enter the target IP address: ")
target_port = int(input("Enter the target port: "))
tcp_handshake(target_ip, target_port)
output:
Enter the target IP address: 192.168.1.10
Enter the target port: 80
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
transmission_success = [False] * num_stations
attempts = [0] * num_stations
while not all(transmission_success):
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!")
# Collision detected, backoff for each station
for station in transmitting_stations:
backoff = random.randint(1, 3)
print(f"Station {station} backing off for {backoff} seconds...")
time.sleep(backoff)
attempts[station] += 1
if attempts[station] >= max_attempts:
print(f"Station {station} failed to transmit after {max_attempts} attempts.")
transmission_success[station] = True
elif len(transmitting_stations) == 1:
# Only one station transmitting — successful transmission
station = transmitting_stations[0]
print(f"\n[Success] Station {station} is transmitting successfully...")
time.sleep(2)
transmission_success[station] = True
else:
break
print("\nAll stations have either transmitted successfully or given up.")
num_stations = int(input("Enter the number of stations: "))
csma_cd_simulation(num_stations)
Output:
Enter the number of stations: 3
[Collision] Stations [0, 1, 2] are transmitting at the same time!
Station 0 backing off for 2 seconds...
Station 1 backing off for 3 seconds...
Station 2 backing off for 1 seconds...
[Success] Station 2 is transmitting successfully...
[Collision] Stations [0, 1] are transmitting at the same time!
Station 0 backing off for 2 seconds...
Station 1 backing off for 1 seconds...
[Success] Station 1 is transmitting successfully...
[Success] Station 0 is transmitting successfully...
All stations have either transmitted successfully or given up.
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
void exponential_backoff(int attempt) {
int max_backoff = (1 << attempt) - 1; // 2^attempt - 1
int backoff_time = rand() % (max_backoff + 1); // Random backoff
printf("Backing off for %d seconds...\n", backoff_time);
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));
for (i = 0; i < MAX_DEVICES; i++) {
devices[i] = 1;
attempts[i] = 0;
transmitted[i] = 0;
printf("Starting CSMA/CD Ethernet Simulation...\n");
while (!all_transmitted) {
colliding_devices = 0;
for (i = 0; i < MAX_DEVICES; i++) {
if (devices[i] && (rand() % 2)) {
colliding_devices++;
if (colliding_devices > 1) {
printf("\nCollision detected! %d devices tried to transmit.\n", colliding_devices);
for (i = 0; i < MAX_DEVICES; i++) {
if (devices[i] && (rand() % 2)) {
attempts[i]++;
if (attempts[i] > MAX_ATTEMPTS) {
printf("Device %d failed after %d attempts. Giving up.\n", i, attempts[i]);
devices[i] = 0;
} else {
printf("Device %d performing exponential backoff (attempt %d).\n", i, attempts[i]);
exponential_backoff(attempts[i]);
} else if (colliding_devices == 1) {
// Only one device is transmitting
for (i = 0; i < MAX_DEVICES; i++) {
if (devices[i] && (rand() % 2)) {
printf("\nDevice %d is transmitting successfully!\n", i);
transmitted[i] = 1;
devices[i] = 0;
break;
} else {
printf("\nNo devices attempting to transmit this round.\n");
all_transmitted = 1;
for (i = 0; i < MAX_DEVICES; i++) {
if (!transmitted[i] && devices[i]) {
all_transmitted = 0;
break;
printf("\nAll devices have either transmitted successfully or given up.\n");
return 0;
Output:
Starting CSMA/CD Ethernet Simulation...
Collision detected! 2 devices tried to transmit.
Device 0 performing exponential backoff (attempt 1).
Backing off for 0 seconds...
Device 1 performing exponential backoff (attempt 1).
Backing off for 1 seconds...
Device 1 is transmitting successfully!
Device 0 is transmitting successfully!
All devices have either transmitted successfully or given up.
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
client_ips = ["192.168.1.2", "192.168.1.3"]
server_ip = "192.168.1.100" # Server IP address
port = 9000
def send_data(ip, message):
try:
print(f"Trying to connect using IP {ip}...")
# Here we simulate connection (real SCTP would use sctp.sctpsocket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((server_ip, port))
sock.sendall(message.encode())
print(f"Message sent successfully using IP {ip}.")
sock.close()
return True
except Exception as e:
print(f"Failed to send using IP {ip}. Error: {e}")
return False
def sctp_multihoming_simulation():
message = "Hello Server! [SCTP Multihoming Simulation]"
active_ip_index = 0 # Start with first IP
while True:
success = send_data(client_ips[active_ip_index], message)
if not success:
print(f"Switching to alternate IP {client_ips[1 - active_ip_index]}...")
active_ip_index = 1 - active_ip_index # Switch IP
success = send_data(client_ips[active_ip_index], message)
if not success:
print("Both connections failed! Transmission unsuccessful.")
break
else:
print("Transmission successful!")
break
time.sleep(2) # Wait before retrying
if __name__ == "__main__":
sctp_multihoming_simulation()
Output:
Trying to connect using IP 192.168.1.2...
Failed to send using IP 192.168.1.2. Error: [Errno 101] Network is unreachable
Switching to alternate IP 192.168.1.3...
Trying to connect using IP 192.168.1.3...
Failed to send using IP 192.168.1.3. Error: [Errno 101] Network is unreachable
Both connections failed! Transmission unsuccessful.
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
from collections import defaultdict, Counter
class Node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(freq_map):
heap = [Node(char, freq) for char, freq in freq_map.items()]
heapq.heapify(heap)
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged = Node(None, left.freq + right.freq)
merged.left = left
merged.right = right
heapq.heappush(heap, merged)
return heap[0]
def generate_codes(node, prefix="", code_map={}):
if node is None:
return
if node.char is not None:
code_map[node.char] = prefix
generate_codes(node.left, prefix + "0", code_map)
generate_codes(node.right, prefix + "1", code_map)
return code_map
def encode_string(input_string, code_map):
return ''.join(code_map[char] for char in input_string)
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)
encoded_string = encode_string(input_string, huffman_codes)
return encoded_string, huffman_codes
if __name__ == "__main__":
input_string = input("Enter a string to encode using Huffman encoding: ")
encoded_string, huffman_codes = huffman_encoding(input_string)
print("\nHuffman Codes:")
for char, code in huffman_codes.items():
print(f"'{char}': {code}")
print(f"\nEncoded String:\n{encoded_string}")
Output:
Enter a string to encode using Huffman encoding: ABRACADABRA
Huffman Codes:
'A': 0
'B': 111
'R': 110
'C': 101
'D': 100
Encoded String:
01111100100001111110110