ICMP
1.windows python ———ICMP
import socket
import struct
def checksum(source_string):
sum = 0
countTo = (len(source_string)/2)*2
count = 0
while count<countTo:
thisVal = ord(source_string[count + 1:count + 2])*256 + ord(source_string[count:count + 1])
sum = sum + thisVal
sum = sum & 0xffffffff
count = count + 2
if countTo<len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def ping(ip):
rawsocket1=socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.getprotobyname("icmp"))
packet = struct.pack('!BBHHH8s', 8, 0, 0, 0, 0, b'abcdefgh')
chksum=checksum(packet)
packet = struct.pack('!BBHHH8s', 8, 0, chksum, 0, 0, b'abcdefgh')
rawsocket1.sendto(packet, (ip, 11111))
data,addr = rawsocket1.recvfrom(1204)
print type(data),addr,"\n",data
by=""
for k in range(1,17):
by+=data[-(17-k)]
print by
pcket=struct.unpack('!BBHHH8s',by)
print pcket
ping('xx.xx.xx.xx')
因为收到的包不仅仅包括ICMP Reply包的16个字节,所以先取出后面的16个
struct
2.关于struct
struct.pack(‘格式’,变量1,变量2…)
对应C语言的格式
注: unsigned char —-BYTE unsigned short—-USHORT