SlideShare a Scribd company logo
Please help with the below 3 questions, the python script is at the bottom, I cannot get it to work
correctly please indicate where the error is. Thanks
Question-01: Approximately how much longer does it take to do a round-trip ping from/to a
remote machine than from/to localhost? (Note, answers may vary if you are doing the
experiment from your home or from the CS building itself and whether the destination is in
North America or some other continent).
Question-02: Currently, the program calculates the round-trip time for each packet and prints it
out individually. Modify this to correspond to the way the standard ping program works. You
will need to report the minimum, maximum, and average RTTs at the end of all pings from the
client. In addition, calculate the packet loss rate (in percentage).
Question-03: Your program can only detect timeouts in receiving ICMP echo responses. Modify
the Pinger program to parse the ICMP response error codes and display the corresponding error
results to the user. Examples of ICMP response error codes are 0: Destination Network
Unreachable, 1: Destination Host Unreachable.
In this lab, you will gain a better understanding of Internet Control Message Protocol (ICMP).
You will learn to implement a Ping application using ICMP request and reply messages. Ping is
a computer network application used to test whether a particular host is reachable across an IP
network. It is also used to self-test the network interface card of the computer or as a latency test.
It works by sending ICMP echo reply packets to the target host and listening for ICMP echo
reply replies. The "echo reply" is sometimes called a pong. Ping measures the round-trip time,
records packet loss, and prints a statistical summary of the echo reply packets received (the
minimum, maximum, and the mean of the round-trip times and in some versions the standard
deviation of the mean).
Your task is to develop your own Ping application in Python. Your application will use ICMP
but, in order to keep it simple, will not exactly follow the official specification in RFC 1739.
Note that you will only need to write the client side of the program, as the functionality needed
on the server side is built into almost all operating systems. You should complete the Ping
application so that it sends ping requests to a specified host separated by approximately one
second. Each message contains a payload of data that includes a timestamp. After sending each
packet, the application waits up to one second to receive a reply. If one second goes by without a
reply from the server, then the client assumes that either the ping packet or the pong packet was
lost in the network (or that the server is down).
This lab requires you to compose new python code. A skeleton framework is given, you will
need to fill in the blanks.
This lab will require you to build and/or decode a packed binary array of data that is specified by
the ICMP protocol. To assist you, the ICMP protocol specification is copied verbatim from RFC
792, September 1981.
privileges to be able to run your Pinger program. Therefore you will need to do a "sudo"
command on your own laptop, or use the VM machines we have set up for you and do a "sudo"
with the VM. This also implies that you should save and edit the code on your machine (or the
VM). You cannot run the code directly from this jupyter lab because, as far as I know, you can't
do a sudo with jupyter. 5. You might want to check your output against a wireshark trace to
make sure the TTL and other parameters that you print are correct. This is optional, but
recommended.
First, test your client by sending packets to localhost, that is, 127.0.0.1. Then, you should see
how your Pinger application communicates across the network by pinging servers in different
continents.
##%%writefile icmpPing.py
from socket import *
import os
import sys
import struct
import time
import select
import binascii
ICMP_ECHO_REQUEST = 8 # the ICMP code number for PING (ECHO REQUEST)
#
# Yay! you don't have to write your own checksum calculation. Just use this routine as is.
#
def checksum(checksum_packet):
"""Calculate checksum"""
total = 0
# Add up 16-bit words
num_words = len(checksum_packet) // 2
for chunk in struct.unpack("!%sH" % num_words, checksum_packet[0:num_words*2]):
total += chunk
# Add any left over byte
if len(checksum_packet) % 2:
total += ord(checksum_packet[-1]) << 8
# Fold 32-bits into 16-bits
# Note the offset: in C this would return as a uint16_t type, but Python
# returns it as signed which puts it in the wrong range for struct.pack's H cast
# Adding the 0xffff offset moves it into the correct range, while the mask removes any
overflow.
total = (total >> 16) + (total & 0xffff)
total += total >> 16
return (~total + 0x10000 & 0xffff)
#
# Receive and process an echo reply
# You will have to add code to this skeleton
#
def receiveOnePing(mySocket, ID, timeout, destAddr):
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return "Request timed out."
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
#accessing icmp header from packet
icmpHeader = recPacket[20:28]
icmpType, code, mychecksum, packetID, sequence = struct.unpack("bbHHh", icmpHeader)
#verify the ID of packet
if icmpType != 8 and packetID == ID:
bytesInDouble = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
return timeReceived - timeSent
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out."
#
# send an echo request
# you do not have to add code to this routine
#
def sendOnePing(mySocket, destAddr, ID):
# Header is defined as: type (8), code (8), checksum (16), id (16), sequence (16)
# Make a dummy header with a 0 checksum
myChecksum = 0
# struct -- Interpret strings as packed binary data that complies with the header format
# and uses a data payload containing the time in packed binary format as well.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
# Convert 16-bit integers from host to network byte order
myChecksum = htons(myChecksum) & 0xffff
else:
myChecksum = htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1))
# AF_INET address must be tuple, not str
# Both LISTS and TUPLES consist of a number of objects
# which can be referenced by their position number within the object.
#
# perform a single ping and receive a pong
# you do not have to change any code in this routine
#
def doOnePing(destAddr, timeout):
icmp = getprotobyname("icmp")
# SOCK_RAW is a powerful socket type. For more details: http://sock-
raw.org/papers/sock_raw
mySocket = socket(AF_INET, SOCK_RAW, icmp)
myID = os.getpid() & 0xFFFF #Return the current process
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
def ping(host, timeout=1):
# timeout=1 means: If one second goes by without a reply from the server,
# the client assumes that either the client's ping or the server's pong is lost
dest = gethostbyname(host)
print("Pinging " + dest + " using Python:")
print("")
# Send ping requests to a server separated by approximately one second
while 1 :
delay = doOnePing(dest, timeout)
print(delay)
time.sleep(1) # one second
return delay
# Finally ! ping google. Try out other sites as well.
##ping("google.com")
'''
#Picked IP of different continent from:
#https://www.dotcom-monitor.com/blog/technical-tools/network-location-ip-addresses/
print("Ping to Washington DC")
ping("23.81.0.59")#Washington DC
print('-----------------------')
print("Ping to China")
ping("www.china.org.cn") #china
print('-----------------------')
print("Ping to Australia")
ping("223.252.19.130") # Brisbane, Australia
print('-----------------------')
print("Ping to Europe")
ping("95.142.107.181") #Amsterdam
'''
----------------My output-----------------
Pinging 142.250.217.142 using Python:
0.21144652366638184
0.1824963092803955
0.036752939224243164
0.05558586120605469
0.10225915908813477
0.03284192085266113
0.11963796615600586
0.06659841537475586
0.09904909133911133

More Related Content

PPTX
Internet control message protocol (ICMP)
ODP
Code Red Security
PDF
Ping to Pong
PDF
Maxbox starter18
DOCX
Remote Procedure Call
PPT
Cs423 raw sockets_bw
PDF
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
PDF
Advanced RAC troubleshooting: Network
Internet control message protocol (ICMP)
Code Red Security
Ping to Pong
Maxbox starter18
Remote Procedure Call
Cs423 raw sockets_bw
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
Advanced RAC troubleshooting: Network

Similar to Please help with the below 3 questions, the python script is at the.pdf (20)

PPTX
PACKET Sniffer IMPLEMENTATION
DOC
PDF
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
DOCX
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
DOCX
Lab3 advanced port scanning 30 oct 21
PDF
Socket programming
PDF
Figure 3 TCP Session Hijacking Attack victims to execute the mali.pdf
PPT
OSTU - hrPING QuickStart Part 1 (by Tony Fortunato & Peter Ciuffreda)
PPT
In depth understanding network security
PPT
Troubleshooting basic networks
PDF
Arduino Teaching Program
PPTX
Information gathering using windows command line utility
PDF
Pycon - Python for ethical hackers
PDF
Wireshark ip sept_15_2009
PDF
100 bugs in Open Source C/C++ projects
PDF
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
PDF
Real-time in the real world: DIRT in production
PDF
Buffer overflow tutorial
PACKET Sniffer IMPLEMENTATION
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
Lab3 advanced port scanning 30 oct 21
Socket programming
Figure 3 TCP Session Hijacking Attack victims to execute the mali.pdf
OSTU - hrPING QuickStart Part 1 (by Tony Fortunato & Peter Ciuffreda)
In depth understanding network security
Troubleshooting basic networks
Arduino Teaching Program
Information gathering using windows command line utility
Pycon - Python for ethical hackers
Wireshark ip sept_15_2009
100 bugs in Open Source C/C++ projects
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
Real-time in the real world: DIRT in production
Buffer overflow tutorial
Ad

More from support58 (10)

PDF
Please show me your output. Andrew Kelly has been employed by the We.pdf
PDF
Please show me how to do every part of this. Also could you show me .pdf
PDF
please help! Carmen Company has the following projected costs for .pdf
PDF
Please help will upvote. I have a heuristic function that outputs th.pdf
PDF
Please create a simple flowchart of this programtell me the necess.pdf
PDF
Please complete ALL of the �TO DO�s in this code. I am really strugg.pdf
PDF
Please answer ASAP!!!Research Topic Ransomware attack on k-12 sch.pdf
PDF
Plan production for a four-month period (February through May). .pdf
PDF
Part I.pdf
PDF
Part 1 During the most recent economic crisis in the state of Arizo.pdf
Please show me your output. Andrew Kelly has been employed by the We.pdf
Please show me how to do every part of this. Also could you show me .pdf
please help! Carmen Company has the following projected costs for .pdf
Please help will upvote. I have a heuristic function that outputs th.pdf
Please create a simple flowchart of this programtell me the necess.pdf
Please complete ALL of the �TO DO�s in this code. I am really strugg.pdf
Please answer ASAP!!!Research Topic Ransomware attack on k-12 sch.pdf
Plan production for a four-month period (February through May). .pdf
Part I.pdf
Part 1 During the most recent economic crisis in the state of Arizo.pdf
Ad

Recently uploaded (20)

PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Institutional Correction lecture only . . .
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Structure & Organelles in detailed.
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Insiders guide to clinical Medicine.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
master seminar digital applications in india
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
RMMM.pdf make it easy to upload and study
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
O5-L3 Freight Transport Ops (International) V1.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Complications of Minimal Access Surgery at WLH
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Institutional Correction lecture only . . .
Anesthesia in Laparoscopic Surgery in India
Cell Structure & Organelles in detailed.
01-Introduction-to-Information-Management.pdf
Pharma ospi slides which help in ospi learning
Microbial diseases, their pathogenesis and prophylaxis
Insiders guide to clinical Medicine.pdf
Sports Quiz easy sports quiz sports quiz
Renaissance Architecture: A Journey from Faith to Humanism
master seminar digital applications in india
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf

Please help with the below 3 questions, the python script is at the.pdf

  • 1. Please help with the below 3 questions, the python script is at the bottom, I cannot get it to work correctly please indicate where the error is. Thanks Question-01: Approximately how much longer does it take to do a round-trip ping from/to a remote machine than from/to localhost? (Note, answers may vary if you are doing the experiment from your home or from the CS building itself and whether the destination is in North America or some other continent). Question-02: Currently, the program calculates the round-trip time for each packet and prints it out individually. Modify this to correspond to the way the standard ping program works. You will need to report the minimum, maximum, and average RTTs at the end of all pings from the client. In addition, calculate the packet loss rate (in percentage). Question-03: Your program can only detect timeouts in receiving ICMP echo responses. Modify the Pinger program to parse the ICMP response error codes and display the corresponding error results to the user. Examples of ICMP response error codes are 0: Destination Network Unreachable, 1: Destination Host Unreachable. In this lab, you will gain a better understanding of Internet Control Message Protocol (ICMP). You will learn to implement a Ping application using ICMP request and reply messages. Ping is a computer network application used to test whether a particular host is reachable across an IP network. It is also used to self-test the network interface card of the computer or as a latency test. It works by sending ICMP echo reply packets to the target host and listening for ICMP echo reply replies. The "echo reply" is sometimes called a pong. Ping measures the round-trip time, records packet loss, and prints a statistical summary of the echo reply packets received (the minimum, maximum, and the mean of the round-trip times and in some versions the standard deviation of the mean). Your task is to develop your own Ping application in Python. Your application will use ICMP but, in order to keep it simple, will not exactly follow the official specification in RFC 1739. Note that you will only need to write the client side of the program, as the functionality needed on the server side is built into almost all operating systems. You should complete the Ping application so that it sends ping requests to a specified host separated by approximately one second. Each message contains a payload of data that includes a timestamp. After sending each packet, the application waits up to one second to receive a reply. If one second goes by without a reply from the server, then the client assumes that either the ping packet or the pong packet was lost in the network (or that the server is down).
  • 2. This lab requires you to compose new python code. A skeleton framework is given, you will need to fill in the blanks. This lab will require you to build and/or decode a packed binary array of data that is specified by the ICMP protocol. To assist you, the ICMP protocol specification is copied verbatim from RFC 792, September 1981. privileges to be able to run your Pinger program. Therefore you will need to do a "sudo" command on your own laptop, or use the VM machines we have set up for you and do a "sudo" with the VM. This also implies that you should save and edit the code on your machine (or the VM). You cannot run the code directly from this jupyter lab because, as far as I know, you can't do a sudo with jupyter. 5. You might want to check your output against a wireshark trace to make sure the TTL and other parameters that you print are correct. This is optional, but recommended. First, test your client by sending packets to localhost, that is, 127.0.0.1. Then, you should see how your Pinger application communicates across the network by pinging servers in different continents. ##%%writefile icmpPing.py from socket import * import os import sys import struct import time import select import binascii ICMP_ECHO_REQUEST = 8 # the ICMP code number for PING (ECHO REQUEST) # # Yay! you don't have to write your own checksum calculation. Just use this routine as is. # def checksum(checksum_packet): """Calculate checksum""" total = 0 # Add up 16-bit words num_words = len(checksum_packet) // 2 for chunk in struct.unpack("!%sH" % num_words, checksum_packet[0:num_words*2]): total += chunk # Add any left over byte if len(checksum_packet) % 2:
  • 3. total += ord(checksum_packet[-1]) << 8 # Fold 32-bits into 16-bits # Note the offset: in C this would return as a uint16_t type, but Python # returns it as signed which puts it in the wrong range for struct.pack's H cast # Adding the 0xffff offset moves it into the correct range, while the mask removes any overflow. total = (total >> 16) + (total & 0xffff) total += total >> 16 return (~total + 0x10000 & 0xffff) # # Receive and process an echo reply # You will have to add code to this skeleton # def receiveOnePing(mySocket, ID, timeout, destAddr): timeLeft = timeout while 1: startedSelect = time.time() whatReady = select.select([mySocket], [], [], timeLeft) howLongInSelect = (time.time() - startedSelect) if whatReady[0] == []: # Timeout return "Request timed out." timeReceived = time.time() recPacket, addr = mySocket.recvfrom(1024) #accessing icmp header from packet icmpHeader = recPacket[20:28] icmpType, code, mychecksum, packetID, sequence = struct.unpack("bbHHh", icmpHeader) #verify the ID of packet if icmpType != 8 and packetID == ID: bytesInDouble = struct.calcsize("d") timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0] return timeReceived - timeSent timeLeft = timeLeft - howLongInSelect if timeLeft <= 0: return "Request timed out."
  • 4. # # send an echo request # you do not have to add code to this routine # def sendOnePing(mySocket, destAddr, ID): # Header is defined as: type (8), code (8), checksum (16), id (16), sequence (16) # Make a dummy header with a 0 checksum myChecksum = 0 # struct -- Interpret strings as packed binary data that complies with the header format # and uses a data payload containing the time in packed binary format as well. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) data = struct.pack("d", time.time()) # Calculate the checksum on the data and the dummy header. myChecksum = checksum(header + data) # Get the right checksum, and put in the header if sys.platform == 'darwin': # Convert 16-bit integers from host to network byte order myChecksum = htons(myChecksum) & 0xffff else: myChecksum = htons(myChecksum) header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1) packet = header + data mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str # Both LISTS and TUPLES consist of a number of objects # which can be referenced by their position number within the object. # # perform a single ping and receive a pong
  • 5. # you do not have to change any code in this routine # def doOnePing(destAddr, timeout): icmp = getprotobyname("icmp") # SOCK_RAW is a powerful socket type. For more details: http://sock- raw.org/papers/sock_raw mySocket = socket(AF_INET, SOCK_RAW, icmp) myID = os.getpid() & 0xFFFF #Return the current process sendOnePing(mySocket, destAddr, myID) delay = receiveOnePing(mySocket, myID, timeout, destAddr) mySocket.close() return delay def ping(host, timeout=1): # timeout=1 means: If one second goes by without a reply from the server, # the client assumes that either the client's ping or the server's pong is lost dest = gethostbyname(host) print("Pinging " + dest + " using Python:") print("") # Send ping requests to a server separated by approximately one second while 1 : delay = doOnePing(dest, timeout) print(delay) time.sleep(1) # one second return delay # Finally ! ping google. Try out other sites as well. ##ping("google.com") ''' #Picked IP of different continent from: #https://www.dotcom-monitor.com/blog/technical-tools/network-location-ip-addresses/
  • 6. print("Ping to Washington DC") ping("23.81.0.59")#Washington DC print('-----------------------') print("Ping to China") ping("www.china.org.cn") #china print('-----------------------') print("Ping to Australia") ping("223.252.19.130") # Brisbane, Australia print('-----------------------') print("Ping to Europe") ping("95.142.107.181") #Amsterdam ''' ----------------My output----------------- Pinging 142.250.217.142 using Python: 0.21144652366638184 0.1824963092803955 0.036752939224243164 0.05558586120605469 0.10225915908813477 0.03284192085266113 0.11963796615600586 0.06659841537475586 0.09904909133911133