Question

In: Computer Science

Coding Project 2: UDP Pinger In this lab, you will learn the basics of socket programming...

Coding Project 2: UDP Pinger

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.

You will first study a simple Internet ping server written in the Python, and implement a corresponding client. The functionality provided by these programs is similar to the functionality provided by standard ping programs available in modern operating systems. However, these programs use a simpler protocol, UDP, rather than the standard Internet Control Message Protocol (ICMP) to communicate with each other. The ping protocol allows a client machine to send a packet of data to a remote machine, and have the remote machine return the data back to the client unchanged (an action referred to as echoing). Among other uses, the ping protocol allows hosts to determine round-trip times to other machines.

You are given the complete code for the Ping server below. Your task is to write the Ping client.

Server Code

The following code fully implements a ping server. You need to compile and run this code before running your client program. You do not need to modify this code.

In this server code, 30% of the client’s packets are simulated to be lost. You should study this code carefully, as it will help you write your ping client.

# UDPPingerServer.py


# We will need the following module to generate randomized lost packets import random
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(('', 12000))

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)
# 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)

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.

Packet Loss

UDP provides applications with an unreliable transport service. Messages may get lost in the network due to router queue overflows, faulty hardware or some other reasons. Because packet loss is rare or even non-existent in typical campus networks, the server in this lab injects artificial loss to simulate the effects of network packet loss. The server creates a variable randomized integer which determines whether a particular incoming packet is lost or not.

Client Code

You need to implement the following client program.
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 cannot 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 received within one second, your client program should assume that the packet was lost during transmission across the network. You will need to look up the Python documentation to find out how to set the timeout value on a datagram socket.

Specifically, your client program should
(1) send the ping message using UDP (Note: Unlike TCP, you do not need to establish a connection first, since UDP is a connectionless protocol.)
(2) print the response message from server, if any
(3) calculate and print the round trip time (RTT), in seconds, of each packet, if server responses
(4) otherwise, print “Request timed out”

During development, you should run the UDPPingerServer.py on your machine, and test your client by sending packets to localhost (or, 127.0.0.1). After you have fully debugged your code, you should see how your application communicates across the network with the ping server and ping client running on different machines.

Message Format

The ping messages sent to the server in this project are formatted in a simple way. The client message is one line, consisting of ASCII characters in the following format:

Ping sequence_number time

where sequence_number starts at 1 and progresses to 10 for each successive ping message sent by the client, and time is the time when the client sends the message.

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

I cannot get my version to work, please follow the instructions.

Solutions

Expert Solution

ANSWER:

import socket
from socket import AF_INET, SOCK_DGRAM
import time
print 'Running'

serverName = '127.0.0.1' #server set as localhost
clientSocket = socket.socket(AF_INET,SOCK_DGRAM) #create the socket
clientSocket.settimeout(1) #sets the timeout at 1 sec
sequence_number = 1 #variable to keep track of the sequence number
rtt=[] # list to store the rtt values

while sequence_number<=10:
    start=time.time() #the current time
    message = ('PING %d %d' % (sequence_number, start)) #client message
    clientSocket.sendto(message,(serverName, 11046))#client sends a message to the server
    try:
        message, address = clientSocket.recvfrom(1024) #recieves message from server
        elapsed = (time.time()-start) # calculates the rtt
        rtt.append(elapsed)
        print message
        print 'Round Trip Time is:' + str(elapsed) + ' seconds'
    except socket.timeout: #if no reply within 1 second
        print message
        print 'Request timed out'
    sequence_number+=1 #incremented by 1
  
    if sequence_number > 10: #closes the socket after 10 packets
        mean=sum(rtt, 0.0)/ len(rtt)
        print ''
        print 'Maximum RTT is:' + str(max(rtt)) + ' seconds'
        print 'Minimum RTT is:' + str(min(rtt)) + ' seconds'
        print 'Average RTT is:' + str(mean)+ ' seconds'
        print 'Packet loss rate is:' + str((10-len(rtt))*10)+ ' percent'
        clientSocket.close()

UDPPinglerServer.py

# UDPPingerServer.py
# We will need the following module to generate randomized lost packets
import random
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(('', 11046))

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)
    # 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)


Related Solutions

In this homework, you will practice and reinforce the basics of socket programming for TCP connections...
In this homework, you will practice and reinforce the basics of socket programming for TCP connections in Python: how to create a socket, bind it to a specific address and port, as well as send and receive a HTTP packet. You will also learn some basics of HTTP header format. The requirements for this homework are specified below. 1. Function Requirement: You will develop a web server that handles one HTTP request at a time. Your web server should accept...
1. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Why might you...
1. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Why might you prefer to run such an application using a UDP transport layer? 2. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Suppose you chose to use TCP for your application; what would you need to do to ensure that the robust transport algorithm does not harm real-time performance?
Learn by Doing Matched Pairs: In this lab you will learn how to conduct a matched...
Learn by Doing Matched Pairs: In this lab you will learn how to conduct a matched pairs T-test for a population mean using StatCrunch. We will work with a data set that has historical importance in the development of the T-test. Paired T hypothesis test: μD = μ1 - μ2 : Mean of the difference between Regular seed and Kiln-dried seed H0 : μD = 0 HA : μD > 0 Hypothesis test results: Difference Mean Std. Err. DF T-Stat...
In this lab, you will explore some basics of Solidwork. 1. Create the numbers 0 –...
In this lab, you will explore some basics of Solidwork. 1. Create the numbers 0 – 9 with lines and arcs 2. Create a polygon with 5 sides and with 9 sides 3. Create two lines with the interior angle between the lines of 145º 4. Create a centerline inside a 4-sided polygon 5. Create a circle of 5 inches in diameter and extrude it for 12 inches in height. Type your name on the surface and extrude cut it...
-What did you learn about Medical Coding and the Purpose of ICD-9-CM?
-What did you learn about Medical Coding and the Purpose of ICD-9-CM?
Goal: in this lab, you will learn to configure sudo to allow a user mrussell to...
Goal: in this lab, you will learn to configure sudo to allow a user mrussell to change password for users. Please follow the steps and answer all the questions at the end of the lab instruction. In the Linux machine ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. For this part you will need a 2nd normal user (non-root) account. If you don't have an account for "auser" with password “room1202” yet, you can create one by running (as room1202): $ sudo useradd -c "A User"...
The Problem Statement In this lab section, you are going to learn how to sort an...
The Problem Statement In this lab section, you are going to learn how to sort an array of integers, and to sort an array of objects. We are going to divide the work into two parts. Part 1. Sorting an array of integers using selection sort In this part, you are given the code (see List 1) for sorting an array of integers into ascending order. The sorting method used is the selection sort. You can cut-and-paste the code into...
In this week’s project, you have reviewed the basics of how the finances of a corporation...
In this week’s project, you have reviewed the basics of how the finances of a corporation work. Posted below is the trading symbol of a corporation. Research, discuss, and analyze that corporation’s equity and debt structure, history, and its current market presence. Be sure to include your recommendations regarding this corporation as a worthwhile investment. Review and comment on your classmates’ work.   The corporation for analysis this week is: Apple Computer Inc (Stock Symbol: AAPL)
Project objective: To learn more about OS scheduling through a hands-on simulation programming experience Implement the...
Project objective: To learn more about OS scheduling through a hands-on simulation programming experience Implement the following 3 CPU scheduling algorithms Simulate and evaluate each with the set of eight processes below. Use any programming language. The program listing should be submitted with the report. FCFS non-preemptive (partial results provided) SJF non-preemptive MLFQ Multilevel Feedback Queue (absolute priority in higher queues)             Queue 1 uses RR scheduling with Tq = 5             Queue 2 uses RR scheduling with Tq =...
Portfolio Project Option #2 is for accounting students who are intuitive learners by nature. You learn...
Portfolio Project Option #2 is for accounting students who are intuitive learners by nature. You learn best from abstract materials like theories and concepts, enjoy challenges, and tend to be more innovative. For this assignment, you are required to complete the accounting case for Denver Works Co in Part 1, KPWC Service in Part 2, and Virginia Company in Part 3. Follow the additional instructions provided below. Part 1: Denver Works Co, a global marketing company, completed the following transactions...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT