Assignment 3 CN Lab

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

SWE 2002 Computer Networks Lab

Assessment-3
Name:jahnavi tulasi.pathella
Reg.no:21MIS0019
1.Implement a TCP based server program to authenticate the client’s User
Name and
Password. The validity of the client must be sent as the reply message to the
client and
display it on the standard output.
Servercode:
import socket
s=socket.socket()
host=socket.gethostname()
port=14442
s.bind((host,port))
s.listen(5)
user=["AAA123","BBB456","CCC789"]
while True:
c,addr=s.accept()
up=c.recv(1024)
pd=c.recv(1024)
un=up+pd
if un in user:
c.send("welcome"+up)
else:
c.send("wrong credentials")
client code:
import socket
s=socket.socket()
host=socket.gethostname()
port=14442
s.connect((host,port))
up=raw_input("enter the user name:")
s.send(up)
pd=raw_input("enter the password:")
s.send(pd)
msg=s.recv(1024)
print msg
output:

2. A student wants to update his name in the register. He sends his request to
his master
specifying his first name and last name. Help the master to concatenate the
names and update
the same in the register. Display the updated name along with the number of
vowels
presented in the name and length of the updated name. Write a client-server
TCP program.
server code:
import socket
s = socket.socket()
host = socket.gethostname()
port = 25133
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
cn = 0
fn = c.recv(1024).decode()
ln = c.recv(1024).decode()
tn = fn + ln
for i in tn:
if (i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'):
cn = cn + 1
else:
pass
print('Updated name:', tn)
print('Number of vowels:', cn)
print('length of name:', len(tn))
c.close()
clientcode:
import socket
s = socket.socket()
host = socket.gethostname()
port = 25133
s.connect((host, port))
print('Enter first name:')
fn = input('')
print('Enter last name:')
ln = input('')
s.send(fn.encode())
s.send(ln.encode())

output:

3. Write a TCP program to create a codeword using simple parity check


mechanism.
Server code:
import socket
s = socket.socket()
s.bind(("10.30.135.70",12347))
s.listen(5)
while True:
c, addr = s.accept()
dw = c.recv(1024)
count, parity_bit = 0, "0"
for i in dw:
count += 1 if i=="1" else 0
if count%2 == 1:
parity_bit = "1"
c.send("Code Word is: "+dw+parity_bit)
client code:
import socket
s = socket.socket()
s.connect(("10.30.135.70",12347))
s.send(raw_input("Enter DataWord: "))
print(s.recv(1024))
output:

4. Implement a TCP/IP based Python code for checking the message sent by the
sender is
erroneous or not through CRC mechanism. The process is defined as follows,
a) Take the input for divisor (Generator) at client program and send it to server,
so that in both the programs the same divisor can be used
b) Client has the message 1100000110000000 to be sent, find the CRC to be
appended to this message, finally create the codeword by adding the CRC to
the original message and sent that codeword to the server.
c) In the Server program manually change the fifth and ninth bit from the left
of the codeword received from the client and then check whether the CRC
mechanism can detect the error or not.
serverCode:
#!/usr/bin/python
import socket
import os
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print ('Got connected from'), addr
c.send('Thank you for connecting')
div = c.recv(1024).decode()
number = c.recv(1024).decode()
numlen = len(number)
divlen = len(div)
number = list(number)
newcode = []
diff = numlen - divlen
newdiff = diff - 1
for i in range(newdiff, numlen ):
newcode.append(number[i])
if(number[-5] == '0'):
number[-5] = '1'
else:
number[-5] = '0'
if(number[-9] == '0'):
number[-9] = '1'
else:
number[-9] = '0'
for i in range(0, divlen):
number.pop
num = ''.join(number)
code = ''.join(newcode)
def crc(number, div, code):
msg = msg + code
msg = list(msg)
div = list(div)
for i in range(len(msg)-len(code)):
if msg[i] == '1':
for j in range(len(div)):
msg[i+j] = str((int(msg[i+j])+int(div[j]))%2)
'return'.join(msg[-len(code):])
code = crc(num, div, code)
check = '0'
newdivlen = divlen - 1
for i in range(0, newdivlen):
check = check + '0'
if(code == check):
print('Error not detected')
else:
print('Error detected')
c.close()
client code:
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
div =("Enter the divisor.")
number = "1100000110000000"
s.connect((host, port))
s.send(div.encode())
def crc(msg, div, code='000'):
msg = msg + code
msg = list(msg)
div = list(div)
for i in range(len(msg)-len(code)):
if msg[i] == '1':
for j in range(len(div)):
msg[i+j] = int((int(msg[i+j])+int(div[j]))%2)
return''.join(msg[-len(code):])
code = crc(number, div)
number = (number + code)
print('The codeword is: ', number)
s.send(number.encode())
s.close()
output:

5. Write a UDP program to build a chat application between client and server.
Server code:
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
serverSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
serverSock.bind((UDP_IP_ADDRESS,UDP_PORT_NO))
while True:
data, addr = serverSock.recvfrom(1024)
print"message:"+data
client code:
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
Message = "Hello Server"
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSock.sendto(Message, (UDP_IP_ADDRESS, UDP_PORT_NO))
Output:
6. Write a UDP program to reverse your name sent by the client.
Server code:
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
while True:
data, addr = serverSock.recvfrom(1024)
name=data.decode()
print('Name to be Reversed',name)
reverse=name[::-1]
serverSock.sendto((reverse.encode()),addr)
serverSock.close()
Client code:
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
name = input('Enter name to be reversed:')
clientSock.sendto((name.encode()),(UDP_IP_ADDRESS, UDP_PORT_NO))
reverse=clientSock.recv(1024)
print('Reversed name:',reverse.decode())
clientSock.close()
Output:

7. Write a UDP based server code to get the date of birth of the client and
calculate the
age as on today. Client has to enter year, month and day of birth. For example,
if the
date of birth of a user is 1/07/2001 then his age is 14 years 0 months and 17
days if
today's date is 18/07/2015. Get today's date from the server.

Server code:
import socket
from datetime import date, datetime
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month,
born.day))
localIP = "127.0.0.1"
localPort = 3000
bufferSize = 1024
UDPServerSocket = socket.socket(family=socket.AF_INET,
type=socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP Server Started at port 3000 at address 127.0.0.1")
while(True):
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0].decode('utf-8')
address = bytesAddressPair[1]
clientInfo = message.split(' ')
clientName = clientInfo[0] + " " + clientInfo[1]
birthday = datetime( int(clientInfo[2]), int(clientInfo[3]), int(clientInfo[4]))
age = calculate_age(birthday)
clientMsg = "Client informationt: Name = {}, Birthdate: {}\nAGE : {}
years".format(clientName, birthday, age)
clientIP = "Client IP Address: {}".format(address)
print(clientMsg)
print(clientIP)
serverResponse = clientMsg
bytesToSend = str.encode(serverResponse)
UDPServerSocket.sendto(bytesToSend, address)
Client code:
import socket
serverAddressPort = ("127.0.0.1", 3000)
bufferSize = 1024
UDPClientSocket = socket.socket(family=socket.AF_INET,
type=socket.SOCK_DGRAM)
if UDPClientSocket:
while True:
fname = input("\nEnter first name: ")
lname = input("\nEnter last name: ")
year = int(input("\nEnter birth year: "))
month = int(input("\nEnter birth month: "))
day = int(input("\nEnter birth day: "))
msgFromClient = fname + " " + lname + " " + str(year) + " " + str(month) + "
" + str(day)

bytesToSend = str.encode(msgFromClient)

UDPClientSocket.sendto(bytesToSend, serverAddressPort
msgFromServer = UDPClientSocket.recvfrom(bufferSize)

msg = "\n\nMessage from Server


\n\n{}".format(msgFromServer[0].decode('utf-8'))

print(msg)

toCont = input("\n\nDo you want to continue or enter exit to stop: ")

if toCont.lower() == "exit":

break
Output:

You might also like