python發送icmp echo requesy請求
代碼如下:
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])*256 + ord(source_string[count])
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):
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, 1)
packet = struct.pack(
"!BBHHH", 8, 0, 0, 0, 0
)
chksum=checksum(packet)
packet = struct.pack(
"!BBHHH", 8, 0, chksum, 0, 0
)
s.sendto(packet, (ip, 1))
if __name__=='__main__':
ping('192.168.41.56')
掃描探測網絡功能(網絡探測器)
代碼如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
探測網絡主機存活。
'''
import os
import struct
import array
import time
import socket
import IPy
import threading
class SendPingThr(threading.Thread):
'''
發送ICMP請求報文的線程。
參數:
ipPool -- 可迭代的IP地址池
icmpPacket -- 構造的icmp報文
icmpSocket -- icmp套字接
timeout -- 設置發送超時
'''
def __init__(self, ipPool, icmpPacket, icmpSocket, timeout=3):
threading.Thread.__init__(self)
self.Sock = icmpSocket
self.ipPool = ipPool
self.packet = icmpPacket
self.timeout = timeout
self.Sock.settimeout( timeout + 3 )
新聞熱點
疑難解答