0% found this document useful (0 votes)
104 views16 pages

Topic - UDP Socket Programming: Assignment: 5

This document contains code for a client program that enables file transfer between two machines using UDP sockets. The client program allows the user to [1] request a list of files from the server, [2] select a file from the list to download, and [3] download the selected file and save it locally while checking for errors. The code handles setting up the UDP socket on the client side, communicating with the server to get the file list and transfer the selected file, and retrying the download if errors occur.

Uploaded by

PREETI -
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)
104 views16 pages

Topic - UDP Socket Programming: Assignment: 5

This document contains code for a client program that enables file transfer between two machines using UDP sockets. The client program allows the user to [1] request a list of files from the server, [2] select a file from the list to download, and [3] download the selected file and save it locally while checking for errors. The code handles setting up the UDP socket on the client side, communicating with the server to get the file list and transfer the selected file, and retrying the download if errors occur.

Uploaded by

PREETI -
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/ 16

Assignment : 5 

-------------------------------------------------------------------------------------------------------------------- 

Name : Preeti 

Div : TY-C 

Roll No : 69 

Batach : B2 

GR Number : 11811321 

Subject : Computer Network Technology Lab Assignment 

----------------------------------------------------------------------------------------------------------- 

Topic - UDP Socket Programming 


------------------------------------------------------------------------------------------------------------------- 
Write a program using UDP Sockets to enable file transfer
(Script, Text, Audio and Video one file each) between two
machines. Capture the packets between client and server
using Wireshark Packet Analyzer Tool for peer to peer mode.
------------------------------------------------------------------------------------------------------------------- 

 
What is UDP ? 
The UDP or User Datagram Protocol, a communication protocol used for transferring 
data across the network. It is an unreliable and connectionless communication protocol 
as it does not establish a proper connection between the client and the server. It is used 
for time-sensitive applications like gaming, playing videos, or Domain Name System 
(DNS) lookups. UDP is a faster communication protocol as compared to the TCP 
 
Some of the features of UDP are: 
● It’s a connectionless communication protocol. 
● It is much faster in comparison with TCP. 
 
This Program will share all types/format of files between client and server. 
Output 
 

 
 
List of all files saved in ServerFiles Folders - 

 
 
 
 
 
 
Server Sent the File to Client and Client Download the file and saved in 
ClientFiles Folder 
 

 
 
 

 
 
Server Side Save Files in the ServerFiles Folder - 

 
 
Client Downloaded Files Saved in ClientFiles Folder - 

 
---------------------------------------------------------------------------------------------------- 
   
Code  
 
Client Side 
 
import socket as sk 
from socket import * 
import os 
import sys 
import hashlib 
import time 
 
SERVER_NAME = "INS" 
os.system('cls' if os.name == 'nt' else 'clear') 
print("starting application.....\n") 
time.sleep(1) 
print() 
print("\t\tComputer Network Technology Lab...") 
time.sleep(0.2) 
print(''' 
   
Welcome To The UDP File Transfer (ALL Type of Files) Assignment''') 
time.sleep(0.1) 
print(''' 
This assignment is done By Preeti TY-C Roll no-69 Batach2 
 
 
Lab 5 : UDP File transfer system 
''') 
time.sleep(0.9) 
print() 
serverIp = None 
def getserverIp(): 
"ask for server ip to enter" 
print("==========================ENTER SERVER-IP==========================") 
time.sleep(0.5) 
print("\t Enter ip of server - you want to connect\n", 
"\t IP must be valid ip\n") 
time.sleep(0.5) 
global serverIp 
serverIp = input("Udp server-ip> ") 
getserverIp() 
 
# Variables used for UDP transfer 
host = "" # For client ip 
clientPort = 10001 # client bind port 
serverAddr = None 
buffer = 1024 # Buffer size of client 
data = "" # Data from server 
filePath = os.getcwd()+ "\\ClientFiles" # Path where files are stored 
saveToFile = "" # filename from server to save 
COUNTER = 0 #no of times file retried to download 
SENDFILE = "" #send file from server 
 
#list of all commands 
LIST = "LIST" # Request for list of files 
FILE = "FILE" # Request for file to send 
NACK = "NACK" # Positive acknowledge regarding file transfer 
PACK = "PACK" # Negatie acnowledge regarding file transfer 
CHECK = "CHECK" # Receive checksum from server 
 
#Getting ip of server 
host = sk.gethostbyname(sk.gethostname()) 
 
#Create server socket 
clientSocket = None 
def initSocket(): 
"Initialize client socket for connecting to server" 
print("Initializing server socket...") 
global clientSocket 
global serverAddr 
global serverIp 
serverAddr = (serverIp,10000) 
clientSocket = None #if second attempts come 
clientSocket = socket(AF_INET, SOCK_DGRAM) 
clientSocket.bind((host,clientPort)) 
initSocket() 
 
#checking for client directory and creating it if not exist 
if not os.path.exists(filePath): 
os.mkdir(filePath) #creating if not exists 
 
def requestList(): 
'Request list of files from the server' 
print("Sending request to server for list of files....") 
try: 
clientSocket.sendto("LIST".encode("utf-8"), serverAddr) 
except Exception: 
os.system('cls' if os.name == 'nt' else 'clear') 
print("\tConnection failed to server...") 
print("\tMaybe ip is wrong...") 
print("\tOr maybe server is closed now...") 
print() 
clientSocket.close() #closing socket first 
getserverIp() #asking to enter ip again 
initSocket() #configure socket again 
return 
print("list of files request has been sent to server.") 
listenForList() #listen for list of files from server 
return 
 
def listenForList(): 
'Wait for list of files by server on request by client' 
print("Waiting for server to send list of files...") 
global serverAddr 
data, serverAddr = clientSocket.recvfrom(buffer) 
time.sleep(0.5) 
print("List of files is received...") 
os.system('cls' if os.name == 'nt' else 'clear') 
allFiles = data.decode("utf-8").strip() # converting data into string of files 
filesList = list(allFiles.split("\t")) 
time.sleep(0.5) 
print("\n\n*******************FILES AVAILABLE ON SERVER************************\n") 
count = 0 
for item in filesList: 
time.sleep(0.1) 
if item.strip() != "": 
count += 1 
print("\t\t",count,". -> ", item, "\n") 
if count == 0: 
print("\t\tNO FILES AVAILABLE") 
return 
time.sleep(0.5) 
print("==========================ENTER FILENAME==========================") 
print("\t filename to download the file.\n", 
"\t Enter name of the file from above list of files...\n") 
time.sleep(0.5) 
sendFile = input("Udp > ") 
global SENDFILE 
SENDFILE = sendFile #for later acknowledge 
saveToFile = filePath+os.sep+sendFile.split('/')[-1] 
print("Sending file name to server....") 
sendFile = "FILE "+ sendFile 
clientSocket.sendto(sendFile.encode("utf-8"), serverAddr) 
 
# goto listen for file 
listenForFile(saveToFile) 
return 
 
def listenForFile(fileName): 
'Wait for file to download and download file from server' 
os.system('cls' if os.name == 'nt' else 'clear') 
fileName = fileName.replace('/','\\') 
print("Waiting for downloading the file...") 
global serverAddr 
data = None 
try: 
global clientSocket 
global serverAddr 
clientSocket.settimeout(2) 
data, serverAddr = clientSocket.recvfrom(buffer) 
except timeout: 
print("Server Busy.") 
print("Server time out...Please try after some time...") 
print("File downloading failed...") 
return 
response = data.decode("utf-8") 
rchecksum = "" 
# if checksum is coming than handle it differently 
if response[:5] == CHECK: 
print("Receiving checksum...") 
rchecksum = response[5:].strip() 
time.sleep(0.5) 
else: 
time.sleep(0.5) 
print("Server reponse -", response) 
print("File not exist on server....") 
print() 
return 
print("checksum received.") 
print(fileName) 
 
file = None 
fileData = None 
try: 
global serverSocket 
clientSocket.settimeout(2) 
fileData, serverAddr = clientSocket.recvfrom(buffer) 
file = open(fileName, "wb+") #Creating file 
except timeout: 
print("Server Busy.") 
print("Server time out...Please try after some time...") 
print("File downloading failed...") 
time.sleep(0.5) 
return 
print("Downloading ", fileName+"...") 
try: 
while True: 
file.write(fileData) 
clientSocket.settimeout(2) 
fileData, serverAddr = clientSocket.recvfrom(buffer) 
except timeout: 
file.close() 
 
# Creating checksum for checking correctness of file 
checkSum = hashlib.md5(open(fileName, "rb").read()).hexdigest() 
if rchecksum == checkSum: 
global COUNTER 
COUNTER = 0 #setting counter to zero - file is downloaded 
time.sleep(0.5) 
print("File Downloading Completed! -",os.path.getsize(fileName), "bytes downloaded.") 
pack = PACK + " " + SENDFILE 
clientSocket.sendto(pack.encode("utf-8"), serverAddr) 
time.sleep(0.5) 
else: 
print("checksum error..") 
return 
os.remove(fileName) 
os.system('cls' if os.name == 'nt' else 'clear') 
print("Error on server...") 
print("File downloading failed.") 
time.sleep(0.5) 
if(COUNTER < 5): 
COUNTER += 1 #increasing counter 
print("Retrying to download the file...") 
time.sleep(0.5) 
nack = NACK + " " + SENDFILE 
clientSocket.sendto(nack.encode("utf-8"), serverAddr) 
listenForFile(fileName) #download file again 
 
def options(): 
'Gives user option to do file transfer.' 
while True: 
time.sleep(0.5) 
print("\n==========================ENTER COMMAND==========================") 
print("\t 'listf' to see list of files available on server\n", 
"\t 'close' to close the application\n") 
time.sleep(0.5) 
command = input("Udp > ") 
if command == "listf": 
requestList() 
elif command == "close": 
closeApp() 
else: 
print("Udp > Command Error") 
continue 
 
def closeApp(): 
"Close this application" 
time.sleep(0.5) 
os.system('cls' if os.name == 'nt' else 'clear') 
print("Udp is going to close...") 
print("Closing socket to server...") 
print("Server disconnected....") 
clientSocket.close() #closing socket 
print("system exiting...") 
sys.exit() #exiting from the system 
print() 
print("\t\tBYE - SEE YOU NEXT TIME") 
print() 
options() 
 
 
Server Side 
 
import socket as sk 
from socket import * 
import os 
import sys 
import hashlib 
import time 
import datetime 
 
os.system('cls' if os.name == 'nt' else 'clear') 
print() 
print("\t\tComputer Network Technology Lab...") 
time.sleep(0.2) 
print(''' 
Welcome To The UDP File Transfer(All Types of Files) Assignment''') 
time.sleep(0.1) 
print(''' 
This assignment is done By Preeti TY-C Roll no-69 Batach2 
 
Lab 5 : UDP File Transfer System 
''') 
time.sleep(0.9) 
print() 
 
# Variables used for UDP transfer 
host = "" # For server ip 
serverPort = 10000 # Server bind port 
clientPort = 10001 # client bind port 
buffer = 1024 # Buffer size of server 
data = "" # Data from client 
filePath = os.getcwd()+ "\\ServerFiles" # Path where files are stored 
logDict = {} #log datastructure for server 
 
#list of all commands 
LIST = "LIST" # Request for list of files 
FILE = "FILE" # Request for file to send 
NACK = "NACK" # Positive acknowledge regarding file transfer 
PACK = "PACK" # Negatie acnowledge regarding file transfer 
CHECK = "CHECK" #sends checksum to client 
 
#Getting ip of server 
host = sk.gethostbyname(sk.gethostname()) 
 
#checking for server directory and creating it if not exist 
if not os.path.exists(filePath): 
os.mkdir(filePath) #creating if not exists 
 
#Create server socket 
print("Initializing server socket...") 
serverSocket = socket(AF_INET, SOCK_DGRAM) 
serverSocket.bind((host,serverPort)) 
 
clientAddr = (host,clientPort) # Temporary saving of server address into client address 
 
def listen(): 
'Server will listen to clients and responde according to the commands' 
print("Waiting for clients on port", serverPort, " for UDP connection...") 
try: 
data,clientAddr = serverSocket.recvfrom(buffer) 
except ConnectionResetError: 
print("Client connection lost due to some reason...") 
listen() #return to listing again 
print("Connected to client - ip:", clientAddr[0], " to port ", clientAddr[1]) 
data = data.decode("utf-8").strip() 
if data == LIST: 
sendList() 
listen() 
elif data[:4] == FILE: 
data = data[5:].strip() 
sendFile(filePath + "\\"+data) 
listen() 
elif data[:4] == NACK: 
print("Data has not been received by client...") 
currentTime = datetime.datetime.now() 
putToLog(currentTime.strftime("%Y-%m-%d %H:%M"), clientAddr, data[4:].strip(),"FAILED") 
 
#resend data to the client 
print("Resending data to the client....") 
sendFile(data[4:].strip()) 
listen() 
elif data[:4] == PACK: 
print("Data has been received by client...") 
currentTime = datetime.datetime.now() 
putToLog(currentTime.strftime("%Y-%m-%d %H:%M"), clientAddr, data[4:].strip(),"SUCCESS") 
listen() 
else: 
print("Command Error from Client: ") 
listen() #listen for clients 
return 
 
def sendList(): 
'Sending list of files from the server' 
print("Reading list of files from the server database....") 
filesList = [] # list of all files on server 
 
for root, dirs, files in os.walk(filePath): 
for file in files: 
relPath = os.path.relpath(root, filePath) 
filesList.append(os.path.join(relPath,file)) 
 
allFiles = "" 
# Converting list of files into long string 
for item in filesList: 
allFiles += item + "\t" 
 
# Sending list of files to the client 
print("Sending list of files to the client - ip: ",clientAddr[0], " to port ", clientAddr[1]) 
serverSocket.sendto(allFiles.encode("utf-8"), clientAddr) 
print("Server sending list of files has been completed...") 
return 
 
def sendFile(fileName): 
'Sending file to the client' 
#read data from file in byte format 
#checking if file is exist or not! 
if not os.path.exists(fileName): 
print("Wrong file requested by client...") 
serverSocket.sendto("Wrong file requested.".encode("utf-8"), clientAddr) 
return 
print("Making checksum for file (md5)...") 
checkSum = hashlib.md5(open(fileName,"rb").read()).hexdigest() 
print("checksum complete.") 
time.sleep(0.5) 
print("Reading file data and sending it to the client....") 
file = open(fileName, "rb") 
print("Sending checksum to the client...") 
checkSum = CHECK + " " + checkSum 
serverSocket.sendto(checkSum.encode("utf-8"), clientAddr) 
print("chcksum has been sent to client - ip: ", clientAddr[0], " to port ", clientAddr[1]) 
print("Sending file in Synchronous mode...") 
fileSize = int(os.path.getsize(fileName)) 
count = int(fileSize/buffer)+1 
print(fileSize) 
print("Sending file", fileName, " to the client...." ) 
time.sleep(0.5) 
while(count != 0) : 
fileData = file.read(buffer) 
serverSocket.sendto(fileData, clientAddr) 
time.sleep(0.02) 
count -= 1 
print("File has been sent to client") 
print() 
file.close() #closing file after sending the file 
time.sleep(0.5) 
 
def putToLog(curDTime, cAddr, fName, message): 
"Save log on the server for file transfer" 
print("Managing log manager of server....") 
tempList = [cAddr,fName, message] 
logDict[curDTime] = tempList #saving in log of server 
print(logDict) 
listen() #listen to client 
 
-------------------------------------------------------------------------------------------------------------------------------------------- 

 
Wireshark Capture 
 

 
 
 

 
 
 
----------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------- 

You might also like