SOCKET PROGRAMMING
LAB ASSIGNMENT : 5
Aim :- SOCKET PROGRAMMING : UDP
In this lab, you will learn the basics of socket programming for
UDP in Python. You will learn how to send and receive datagram packets using UDP sockets and also, how to set a proper socket timeout.
Throughout the lab, you will gain familiarity with a Ping application and its usefulness in computing statistics such as packet loss rate.
Server Code :The following code fully implements a ping server. You need to compile and run this code before running your client program :
#We will need the following module to generate randomized lost packets import random import socket from socket import *
#Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket serverSocket.bind(('', 12555)) while True:
# Generate random number in the range of 0 to 10 rand = random.randint(0, 10)
# Receive the client packet along with the address it is coming from message, address = serverSocket.recvfrom(1024) print message
# Capitalize the message from the client message = message.upper()
#If rand is less is than 4, we consider the packet lost and do not respond if rand < 4: continue # Otherwise, the server responds serverSocket.sendto(message, address)
In this server code, 30% of the client’s packets are simulated to be lost.
The server sits in an infinite loop listening for incoming UDP packets. When a packet comes in and if a randomized integer is greater than or equal to 4, the server simply capitalizes the encapsulated data and sends it back to the client.
Client Code :The client should send 10 pings to the server. Because UDP is an unreliable protocol, a packet sent from the client to the server may be lost in the network, or vice versa . For this reason, the client can not wait indefinitely for a reply to a ping message. You should get the client wait up to one second for a reply; if no reply is