0% found this document useful (0 votes)
10 views

Network programming lab experiments

Network programming lab experiments:

Uploaded by

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

Network programming lab experiments

Network programming lab experiments:

Uploaded by

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

Network programming lab experiments:

Client and server


Client.py Server.py
from socket import * from socket import *
serverName = "127.0.0.1"
serverPort = 12000 serverName= "127.0.0.1"
clientSocket = socket(AF_INET, SOCK_STREAM) serverPort = 12000
clientSocket.connect((serverName,serverPort))
serverSocket = socket(AF_INET,SOCK_STREAM)
sentence = str(input("Enter file name : ")) serverSocket.bind((serverName,serverPort))
clientSocket.send(sentence.encode()) serverSocket.listen(1)
filecontents = print ("The server is ready to receive")
clientSocket.recv(1024).decode() while 1:
print ('From Server:', filecontents) connectionSocket, addr =
clientSocket.close() serverSocket.accept()
sentence =
connectionSocket.recv(1024).decode()
file=open(sentence,"r")
l=file.read(1024)
connectionSocket.send(l.encode())
file.close()
connectionSocket.close()
Concurrent and iterative echo servers
Client1.py Server.py
import socket import socket
import multiprocessing
PORT = 4444
PORT = 4444
clientSocket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM) def handle_client(clientSocket, cliAddr, cnt):
serverAddr = ('127.0.0.1', PORT) print(f"Connection accepted from
{cliAddr[0]}:{cliAddr[1]}")
try: print(f"Clients connected: {cnt}\n")
clientSocket.connect(serverAddr)
print("Connected to Server.\n") clientSocket.send(b"hi client")
clientSocket.close()
while True:
data = clientSocket.recv(1024) def main():
sockfd = socket.socket(socket.AF_INET,
if not data: socket.SOCK_STREAM)
break serverAddr = ('127.0.0.1', PORT)
sockfd.bind(serverAddr)
print(f"Server: {data.decode('utf-8')}") sockfd.listen(10)

except Exception as e: print("Listening...\n")


print(f"Error in connection: {e}")
cnt = 0
finally: while True:
clientSocket.close() clientSocket, cliAddr = sockfd.accept()
cnt += 1
process =
multiprocessing.Process(target=handle_client,
args=(clientSocket, cliAddr, cnt))
process.start()

if __name__ == "__main__":
main()
Diffie hellman key exchange Distance vector
import math class NetworkGraph:
def __init__(self):
def power(a, b, P): self.nodes = set()
return a ** b % P self.edges = {}

def gcd(a, b): def add_edge(self, from_node, to_node, cost):


while b: self.nodes.add(from_node)
a, b = b, a % b self.nodes.add(to_node)
return a self.edges[(from_node, to_node)] = cost

def d_h(P, G): def bellman_ford(graph, source):


a, b = 4, 3 distance = {node: float('inf') for node in
graph.nodes}
print("The value of P:", P) distance[source] = 0
print("The value of G:", G)
print("The private key a for Alice:", a) for _ in range(len(graph.nodes) - 1):
x = power(G, a, P) for from_node, to_node in graph.edges:
print("The private key b for Bob:", b) new_distance = distance[from_node] +
y = power(G, b, P) graph.edges[(from_node, to_node)]
ka = power(y, a, P) if new_distance < distance[to_node]:
kb = power(x, b, P) distance[to_node] = new_distance
print("Secret key for Alice is:", ka)
print("Secret key for Bob is:", kb) return distance

def rsa(p, q): def main():


n=p*q network = NetworkGraph()
phi = (p - 1) * (q - 1) network.add_edge("A", "B", 1)
e=7 network.add_edge("B", "C", 1)
network.add_edge("A", "D", 1)
while gcd(e, phi) != 1: network.add_edge("B", "D", 1)
e += 1 network.add_edge("C", "D", 1)
network.add_edge("C", "E", 1)
d = pow(e, -1, phi) network.add_edge("C", "F", 1)
message = 11 network.add_edge("D", "E", 1)
c = pow(message, e, n) network.add_edge("D", "F", 1)
m = pow(c, d, n) network.add_edge("E", "F", 1)

print("Original Message =", message) source_node = "A"


print("p =", p) distances = bellman_ford(network,
print("q =", q) source_node)
print("n = pq =", n)
print("phi =", phi) for node, distance in distances.items():
print("e =", e) print(f"Distance from {source_node} to
print("d =", d) {node}: {distance}")
print("Encrypted message =", c)
print("Decrypted message =", m) if __name__ == "__main__":
main()
if __name__ == "__main__":
p, q = 13, 11
print("RSA Algorithm:")
rsa(p, q)

print("\n\nDiffie Hellman Algorithm..")


d_h(p, q)
Remote command execution
Client.py Server.py
import socket import socket
import subprocess
serverName = "127.0.0.1"
serverPort = 65431 serverName = "127.0.0.1"
serverPort = 65431
with socket.socket(socket.AF_INET,
socket.SOCK_STREAM) as clientSocket: with socket.socket(socket.AF_INET,
clientSocket.connect((serverName, socket.SOCK_STREAM) as serverSocket:
serverPort)) serverSocket.bind((serverName, serverPort))
serverSocket.listen(1)
while True: print("The server is ready to receive")
command = input('Enter the command (or
"exit" to quit):\n') while True:
if not command: connectionSocket, addr =
print("Empty command") serverSocket.accept()
continue
while True:
clientSocket.send(command.encode()) request =
response = connectionSocket.recv(1024).decode()
clientSocket.recv(1024).decode() print(f'Received the request:\n{request}')
print(f'From Server:\n{response}')
if request == "exit":
if command == "exit": connectionSocket.send('Session
break terminated'.encode())
break

status, output =
subprocess.getstatusoutput(request)
response = output if status == 0 else
f'Error: {output}'

connectionSocket.send(response.encode())

print('Bye')
connectionSocket.close()
Simple multicast routing
Receiver.py Sender.py
from socket import * import socket
import struct import time

socketfd = socket(AF_INET, SOCK_DGRAM,0) multicast_group = ('224.0.0.1', 4321)


socketfd.setsockopt(SOL_SOCKET,
SO_REUSEADDR, 1) sock = socket.socket(socket.AF_INET,
port = 4321 socket.SOCK_DGRAM)
socketfd.bind(("", port)) sock.setsockopt(socket.IPPROTO_IP,
group = '224.0.0.1' socket.IP_MULTICAST_TTL, 16)
mreq = struct.pack("!4sl", inet_aton(group),
INADDR_ANY) while True:
socketfd.setsockopt(IPPROTO_IP, message = input("Enter message for multicast:
IP_ADD_MEMBERSHIP, mreq) ")
print("Waiting for Message") print("Sending message")
while True: sock.sendto(message.encode(),
print(socketfd.recv(1024).decode()) multicast_group)
time.sleep(1)

Error detection and correction


def binary_addition(b, c, carry): def main():
result = [] n = int(input("Enter the number of input
for i in range(len(b) - 1, -1, -1): strings: "))
bit_sum = int(b[i]) + int(c[i]) + int(carry) a = [input("Enter the input binary string: ") for
result.append(str(bit_sum % 2)) _ in range(n)]
carry = str(bit_sum // 2) checksum = []
return result[::-1], carry
print("From Sender side.......")
def sender(a, n, checksum): print("Input Strings are:")
max_len = max(len(x) for x in a) [print(x) for x in a]
a = ['0' * (max_len - len(x)) + x for x in a] sender(a, n, checksum)

carry = '0' print("\n\nFrom Receiver side for the


checksum_result = [] checksum....... " + "".join(checksum))
print(f"Enter {n} input strings:")
for j in range(max_len): a = [input("Enter the input binary string: ") for
b = [x[j] for x in a] _ in range(n)]
result, carry = binary_addition(b, ['0'] * n,
carry) print("Input Strings are:")
checksum_result.extend(result) [print(x) for x in a]
receiver(a, n, checksum)
checksum.extend(['1' if x == '0' else '0' for x in
checksum_result]) if __name__ == "__main__":
main()
print("\nCarry =", carry, "\tChecksum =",
"".join(checksum_result))

def receiver(a, n, checksum):


max_len = len(a[0])

carry = '0'
for j in range(max_len):
b = [x[j] for x in a]
result, carry = binary_addition(b, ['0'] * n,
carry)

checksum_result = ['1' if x == '0' else '0' for x


in result]

if checksum_result != checksum:
print("There is an error detected")
else:
print("There is no error detected")

Gethostbyaddr()

The function gethostbyaddr() is used in network programming to retrieve the hostname corresponding
to a given IP address. It's part of the standard library in many programming languages like C, Python,
and others, and it provides reverse DNS lookup.

You might also like