Skip to content

Instantly share code, notes, and snippets.

@ksato9700
Created December 13, 2011 16:38
Show Gist options
  • Save ksato9700/1472830 to your computer and use it in GitHub Desktop.
Save ksato9700/1472830 to your computer and use it in GitHub Desktop.
ping example
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
import time
import struct
import datetime
def calculate_checksum(s):
csum = reduce(lambda a,b: a+b,
[struct.unpack("!h",s[i*2:(i+1)*2])[0] for i in range(len(s)/2)])
csum = (0xffff & csum) + (csum >> 16)
return 0xffff & ~csum
def ping(ip_addr, icmp_seq):
# create a socket
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
# compose icmp payload
icmp_s_type = 8 # Echo Request
icmp_s_code = 0
icmp_s_id = 1
icmp_s_seq = icmp_seq
icmp_s_data = b"abcdefghijklmnopqrstuvwxyz"
icmp_s_payload = struct.pack("!2B2H", icmp_s_type, icmp_s_code, icmp_s_id, icmp_s_seq)
icmp_s_payload += icmp_s_data
# calculate checksum
csum = calculate_checksum(icmp_s_payload)
#print "CheckSum:", hex(csum)
icmp_s_payload = icmp_s_payload[:4] + struct.pack("!h", csum) + icmp_s_payload[4:]
# send the icmp packet
start_time = datetime.datetime.now()
sock.sendto(icmp_s_payload, ip_addr)
# receive the packet
data = sock.recv(255)[20:]
end_time = datetime.datetime.now()
delta = end_time - start_time
# decompose packet
icmp_r_type, icmp_r_code, icmp_r_checksum, icmp_r_id, icmp_r_seq, icmp_r_data = \
struct.unpack("!2B3H%ds" % (len(data)-8), data)
# check the result
try:
assert(icmp_r_type == 0)
assert(icmp_r_code == 0)
assert(icmp_r_seq == icmp_s_seq)
assert(icmp_r_data == icmp_s_data)
assert(icmp_r_checksum == calculate_checksum(data[:2]+data[4:]))
except AssertionError as e:
print e.args
raise
return len(data), delta.total_seconds() * 1000.0
def main():
ip_addr = ("localhost",0)
for i in range (100):
size, delta = ping(ip_addr, i)
print "%s bytes from %s: icmp_seq=%d time=%0.3f ms" % (size, ip_addr[0], i, delta)
time.sleep(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment