[go: up one dir, main page]

0% found this document useful (0 votes)
9 views15 pages

computer_network04062024[1]

Computer network notes

Uploaded by

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

computer_network04062024[1]

Computer network notes

Uploaded by

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

2.

Multicast and Broadcast Sockets


Multicast Sockets:

 Multicast allows a host to send a single packet to multiple recipients, but


not necessarily to all hosts in the network.
 Multicast addresses are a subset of the IPv4 or IPv6 address space
specifically reserved for multicast communication.
 Unlike broadcast, multicast messages are only received by hosts that have
explicitly joined the multicast group.
 Multicast communication is often used for streaming media, online
gaming, video conferencing, and other applications where multiple
recipients are interested in the same data stream.

Broadcast Sockets:

 In a broadcast communication, a single packet is sent from one host to all


hosts in the network segment.
 Broadcast sockets allow a process to send messages to all hosts on the
same network segment.
 In IPv4, the broadcast address is typically the highest address in the
subnet, where all bits in the host part are set to 1 (e.g., 192.168.1.255 for
the 192.168.1.0/24 subnet).
 Broadcast communication is often used for tasks like service discovery,
such as finding available devices or services on a local network.
3.Implementation of prototype Multithreaded Serve
To implement a prototype of a multithreaded server in Python, you can
use the socket library for handling network connections and threading for
managing multiple connections concurrently. Below is a basic example of
how you can create a simple multithreaded server

import socket

import threading

def handle_client(client_socket, address):

print(f"Accepted connection from {address}")

request = client_socket.recv(1024)

print(f"Received: {request.decode()}")

response = "Hello from the server!"

client_socket.send(response.encode())

client_socket.close()

print(f"Connection with {address} closed")

def main():

host = "127.0.0.1"

port = 12345

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

server_socket.bind((host, port))

server_socket.listen(5)

print(f"Server listening on {host}:{port}")

try:

while

client_socket, address = server_socket.accept()

client_thread = threading.Thread(target=handle_client, args=(client_socket, address))

client_thread.start()
except KeyboardInterrupt:

print("Server shutting down...")

server_socket.close()

if __name__ == "__main__":

main()

This code sets up a basic TCP server that listens on localhost (127.0.0.1) and port 12345.
Each incoming connection is handled in its own thread using the handle_client function.
The server listens for connections indefinitely until interrupted by a keyboard interrupt
(Ctrl+C).

This is a simple example. In a real-world scenario, you might want to implement error
handling, graceful shutdown, and possibly use a thread pool or other concurrency
mechanisms for better scalability and resource management. Additionally, consider security
measures such as input validation and sanitization to prevent potential vulnerabilities.
4.Implementation of Data link Layer flow
control Mechanism (Stop and Wait, Sliding
Window)
The Data Link Layer's flow control mechanisms, including Stop-and-Wait and Sliding
Window, are essential for ensuring reliable data transmission between two connected devices
over a communication channel. Let's briefly discuss each mechanism and then outline their
implementations:

1. Stop-and-Wait:
o In Stop-and-Wait, the sender sends one frame at a time and waits for an
acknowledgment (ACK) from the receiver before sending the next frame.
o If the sender doesn't receive an ACK within a specified timeout period, it
assumes that the frame was lost and retransmits it.
o The receiver sends ACKs for correctly received frames, and it discards
duplicates.

Stop-and-Wait Implementation:
def sender(data):

while data:

frame = data[:FRAME_SIZE] # Break data into frames of fixed size

send_frame(frame)

ack = receive_ack()

if ack:

data = data[FRAME_SIZE:]

else:

continue

def receiver():

while True:

frame = receive_frame()

if is_valid(frame):

send_ack()

deliver_data(frame)
else:

continue

2. Sliding Window:
o Sliding Window is a more efficient flow control mechanism where multiple
frames can be transmitted before waiting for acknowledgments.
o It allows the sender to transmit a specified number of frames (window size)
before receiving acknowledgments.
o Both the sender and receiver maintain a window that slides as new frames are
sent and acknowledged.

Now, let's outline a basic implementation for each:

Sliding Window Implementation:


def sender(data):

base = 0

next_seq_num = 0

while base < len(data):

# Send frames in the window

while next_seq_num < min(base + WINDOW_SIZE, len(data)):

frame = data[next_seq_num]

send_frame(frame, next_seq_num)

next_seq_num += 1

while True:

ack = receive_ack()

if ack >= base:

base = ack + 1

break

def receiver():

base = 0
while True:

frame, seq_num = receive_frame()

if seq_num == base:

deliver_data(frame)

base += 1

send_ack(base)

else:

continue
5.Implementation of Data Link layer error
Detection Mechanism (Cyclic Redundancy check)
Cyclic Redundancy Check (CRC) is a popular error detection mechanism
used at the Data Link Layer to detect errors in transmitted data. Here's a
basic implementation of CRC:

CRC Encoding:

def xor(a, b):

result = []

for i in range(1, len(b)):

if a[i] == b[i]:

result.append('0')

else:

result.append('1')

return ''.join(result)

def mod2div(dividend, divisor):

pick = len(divisor)

tmp = dividend[0:pick]

while pick < len(dividend):

if tmp[0] == '1':

tmp = xor(divisor, tmp) + dividend[pick]

else:

tmp = xor('0'*pick, tmp) + dividend[pick]

pick += 1

if tmp[0] == '1':

tmp = xor(divisor, tmp)

else:

tmp = xor('0'*pick, tmp)

return tmp
def encode_data(data, key):

l_key = len(key)

appended_data = data + '0'*(l_key-1)

remainder = mod2div(appended_data, key)

codeword = data + remainder

return codeword

data = "1101011111"

key = "10011"

print("Original data: ", data)

codeword = encode_data(data, key)

print("Encoded data: ", codeword)

CRC Decoding:

def decode_data(data, key):

remainder = mod2div(data, key)

return remainder

received_data = codeword # This should be the data received including


the CRC

remainder = decode_data(received_data, key)

print("Remainder after decoding: ", remainder)

if remainder == '0'*(len(key)-1):

print("Data is error-free")

else:

print("Data contains errors")

6. Implementation of Data Link layer Error Control


Mechanism
(Selective Repeat, Go Back N Selective Repeat Server
side)

Go-Back-N Protocol:
import socket
import threading
import time
SERVER_ADDRESS = ('localhost', 65432)
WINDOW_SIZE = 4
lock = threading.Lock()
base = 0
next_seq_num = 0
expected_seq_num = 0
buffer = []
def handle_client(client_socket, client_address):
global base, next_seq_num, expected_seq_num, buffer
print(f'Connection from {client_address}')
while True:
data, addr = client_socket.recvfrom(1024)
if not data:
break
seq_num = int(data.decode().split(':')[0])
message = data.decode().split(':')[1]
with lock:
if seq_num == expected_seq_num:
print(f"Received expected packet {seq_num} with
message: {message}")
client_socket.sendto(f"ACK:{seq_num}".encode(),
addr)
expected_seq_num += 1
while expected_seq_num in buffer:
print(f"Delivering buffered packet
{expected_seq_num} with message:
{buffer[expected_seq_num]}")
del buffer[expected_seq_num]
expected_seq_num += 1
else:
print(f"Received out of order packet {seq_num} with
message: {message}, expecting {expected_seq_num}")
buffer[seq_num] = message
client_socket.sendto(f"ACK:{expected_seq_num-
1}".encode(), addr)
client_socket.close()
def start_server():
server_socket = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
server_socket.bind(SERVER_ADDRESS)
print(f"Server is listening on {SERVER_ADDRESS}")
while True:
data, client_address = server_socket.recvfrom(1024)
if data:
client_handler =
threading.Thread(target=handle_client, args=(server_socket,
client_address))
client_handler.start()
start_server()

Selective Repeat Protocol:


import socket
import threading
import time
SERVER_ADDRESS = ('localhost', 65433)
WINDOW_SIZE = 4
lock = threading.Lock()
expected_seq_num = 0
buffer = {}
def handle_client(client_socket, client_address):
global expected_seq_num, buffer
print(f'Connection from {client_address}')
while True:
data, addr = client_socket.recvfrom(1024)
if not data:
break
seq_num = int(data.decode().split(':')[0])
message = data.decode().split(':')[1]
with lock:
if seq_num == expected_seq_num:
print(f"Received expected packet {seq_num} with
message: {message}")
client_socket.sendto(f"ACK:{seq_num}".encode(),
addr)
expected_seq_num += 1
while expected_seq_num in buffer:
print(f"Delivering buffered packet
{expected_seq_num} with message:
{buffer[expected_seq_num]}")
del buffer[expected_seq_num]
expected_seq_num += 1
elif expected_seq_num <= seq_num <
expected_seq_num + WINDOW_SIZE:
print(f"Received out of order packet {seq_num} with
message: {message}")
buffer[seq_num] = message
client_socket.sendto(f"ACK:{seq_num}".encode(),
addr)
else:
print(f"Received packet {seq_num} which is outside
the window")
client_socket.sendto(f"ACK:{expected_seq_num-
1}".encode(), addr)
client_socket.close()
def start_server():
server_socket = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
server_socket.bind(SERVER_ADDRESS)
print(f"Server is listening on {SERVER_ADDRESS}")
while True:
data, client_address = server_socket.recvfrom(1024)
if data:
client_handler =
threading.Thread(target=handle_client, args=(server_socket,
client_address))
client_handler.start()
start_server()

TCP/UDP socket progamming

TCP Socket Programming

TCP Server

import socket

server_address = ('localhost', 65432)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

s.bind(server_address)

s.listen()

print('Server is listening on', server_address)

while True:

connection, client_address = s.accept()

with connection:

print('Connection from', client_address)

while True:

data = connection.recv(1024)

if not data:

break

print('Received:', data.decode())

connection.sendall(data)
TCP Client

import socket

server_address = ('localhost', 65432)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

s.connect(server_address)

try:

message = 'Hello, TCP server!'

print('Sending:', message)

s.sendall(message.encode())

data = s.recv(1024)

print('Received:', data.decode())

finally:

print('Closing connection')

UDP server

import socket

server_address = ('localhost', 65432)

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:

s.bind(server_address)

print('UDP server is listening on', server_address)

while True:

data, client_address = s.recvfrom(1024)

print('Received from', client_address, ':', data.decode())


if data:

sent = s.sendto(data, client_address)

print('Sent back to', client_address, ':', data.decode())

UDP Client
import socket

server_address = ('localhost', 65432)

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:

message = 'Hello, UDP server!'

try:

print('Sending:', message)

sent = s.sendto(message.encode(), server_address)

data, server = s.recvfrom(1024)

print('Received:', data.decode())

finally:

print('Closing socket')

You might also like