2

我正在尝试编写一个程序来监控主机是否处于活动状态。我们可以设置我们要监控的主机的ip段。

现在我使用socket发送icmp数据包,这样我们就可以判断主机是否处于活动状态。并且我使用redis进行缓存。我已经尝试了很多。并且我得到了一些收获,所以我可以肯定地说redis-py模块是与套接字冲突。但是,我不知道如何解决这个问题。

相关代码如下:

class icmpThr(threading.Thread):
  def __init__(self, ipPool, timeout=3, isV6=False):
    threading.Thread.__init__(self)
    self.timeout = timeout
    self.isV6 = isV6

    self.ipPool = ipPool
    self.__id = os.getpid()
    self.__data = struct.pack('d', 0)

  def __checkSum(self, packet):
    cksum = 0
    if len(packet) & 1:
      packet = packet + '\0'
    words = array.array('h', packet)
    for word in words:
      cksum += (word & 0xffff)

    cksum = (cksum >> 16) + (cksum & 0xffff)
    cksum = (cksum >> 16) + (cksum & 0xffff)

    return (~cksum) & 0xffff

  @property
  def __icmpSocket(self):
    if self.isV6:
      Sock = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.getprotobyname("ipv6-icmp"))
    else:
      Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))   #the error raised here
    return Sock

  @property
  def __icmpPacket(self):
    if self.isV6:
      header = struct.pack('BbHHh', 128, 0, 0, self.__id, 0)
    else:
      header = struct.pack('bbHHh', 8, 0, 0, self.__id, 0)
    packet = header + self.__data
    cksum = self.__checkSum(packet)

    if self.isV6:
      header = struct.pack('BbHHh', 128, 0, 0, self.__id, 0)
    else: 
      header = struct.pack('bbHHh', 8, 0, cksum, self.__id, 0)
    return header + self.__data

  def run(self):
    sock = self.__icmpSocket
    packet = self.__icmpPacket

    send = sendThr(packet, self.ipPool, sock)
    recv = recvThr(sock, self.ipPool, send)

    send.start()
    recv.start()

def icmpScan():
  ipDb = redis.Redis(host='localhost',port=6379,db=0)

  ipPool = set(['10.0.0.1'])
  ipDb.set('ip_pool', ipPool)#when I delete this line, it runs well

  icmp = icmpThr(ipPool)

  icmp.start()
  icmp.join()

更何况,我一直在搜索错误10043。它的意思是:协议不支持。

在此处输入图像描述

4

0 回答 0