构造icmp包python-socket-校验和
2019-06-24 本文已影响0人
平解技术控
构造检验和的包,通过抓包看下,发出去的包正常收到了对端的回包,试验成功。校验和需要计算请求头+payload的和
def checksum(source_string):
"""
I'm not too confident that this is right but testing seems
to suggest that it gives the same answers as in_cksum in ping.c
"""
sum = 0
countTo = (len(source_string)/2)*2
count = 0
while count<countTo:
thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
sum = sum + thisVal
sum = sum & 0xffffffff # Necessary?
count = count + 2
if countTo<len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff # Necessary?
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
# generate icmp data
def generate_pkg():
## ICMP pkg header
pkt_id = os.getpid()
ident = 0
pkg_header_pre = struct.pack("!BBHHH", 8, 0, 0, pkt_id, ident)
payload = struct.pack("d", time.time())
pkgheader_check = checksum(pkg_header_pre+payload)
pkg_header = struct.pack("!BBHHH", 8, 0, pkgheader_check, pkt_id, ident)
pkg = pkg_header+payload
return pkg
抓包文件如下
image.png
在完成了基本功能之后,下一步就是要做接收包的功能,取出响应包的时延可视化。多次访问一个IP列表,看下程序的访问时间,性能,还有一步优化,收包功能做完之后,接入算法评选ping延时的链路稳定性。
整体代码如下:
#!/bin/env/python
import socket
import struct
import os
import time
# create icmp socket
def create_socket():
proto = 'ICMP'
try:
icmp_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
print icmp_socket
except Exception as e:
raise e
return icmp_socket
def checksum(source_string):
"""
I'm not too confident that this is right but testing seems
to suggest that it gives the same answers as in_cksum in ping.c
"""
sum = 0
countTo = (len(source_string)/2)*2
count = 0
while count<countTo:
thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
sum = sum + thisVal
sum = sum & 0xffffffff # Necessary?
count = count + 2
if countTo<len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff # Necessary?
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
# generate icmp data
def generate_pkg():
## ICMP pkg header
pkt_id = os.getpid()
ident = 0
pkg_header_pre = struct.pack("!BBHHH", 8, 0, 0, pkt_id, ident)
payload = struct.pack("d", time.time())
pkgheader_check = checksum(pkg_header_pre+payload)
pkg_header = struct.pack("!BBHHH", 8, 0, pkgheader_check, pkt_id, ident)
pkg = pkg_header+payload
return pkg
def send_pkg(icmp_socket,pkt,dst_addr):
icmp_socket.sendto(pkt,dst_addr)
if __name__ == '__main__':
icmp_socket = create_socket()
pkt = generate_pkg()
dst_addr = '61.135.169.121'
real_dst_addr = (dst_addr, 0)
send_pkg(icmp_socket, pkt, real_dst_addr)