當前位置: 首頁>>代碼示例>>Python>>正文


Python addresses.IPAddr類代碼示例

本文整理匯總了Python中pox.lib.addresses.IPAddr的典型用法代碼示例。如果您正苦於以下問題:Python IPAddr類的具體用法?Python IPAddr怎麽用?Python IPAddr使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了IPAddr類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _findSwitchNameAndNetworkOfDest

	def _findSwitchNameAndNetworkOfDest(self, destIp):
		dest = IPAddr(destIp)
		ans = []
		for entry in self.routingTable:
			if dest.inNetwork(entry.network):
				ans.append( (entry.name, entry.network) )
		return ans
開發者ID:cannium,項目名稱:openflow_routing,代碼行數:7,代碼來源:pure.py

示例2: parse

    def parse(self, raw):
        assert isinstance(raw, bytes)
        self.raw = raw
        dlen = len(raw)
        if dlen < arp.MIN_LEN:
            self.msg("(arp parse) warning IP packet data too short to parse header: data len %u" % dlen)
            return

        (self.hwtype, self.prototype, self.hwlen, self.protolen, self.opcode) = struct.unpack("!HHBBH", raw[:8])

        if self.hwtype != arp.HW_TYPE_ETHERNET:
            self.msg("(arp parse) hw type unknown %u" % self.hwtype)
        if self.hwlen != 6:
            self.msg("(arp parse) unknown hw len %u" % self.hwlen)
        else:
            self.hwsrc = EthAddr(raw[8:14])
            self.hwdst = EthAddr(raw[18:24])
        if self.prototype != arp.PROTO_TYPE_IP:
            self.msg("(arp parse) proto type unknown %u" % self.prototype)
        if self.protolen != 4:
            self.msg("(arp parse) unknown proto len %u" % self.protolen)
        else:
            self.protosrc = IPAddr(struct.unpack("!I", raw[14:18])[0])
            self.protodst = IPAddr(struct.unpack("!I", raw[24:28])[0])

        self.next = raw[28:]
        self.parsed = True
開發者ID:XianliangJ,項目名稱:collections,代碼行數:27,代碼來源:arp.py

示例3: parse

    def parse(self, raw):
        assert isinstance(raw, bytes)
        self.next = None # In case of unfinished parsing
        self.raw = raw
        dlen = len(raw)
        if dlen < ipv4.MIN_LEN:
            self.msg('warning IP packet data too short to parse header: data len %u' % (dlen,))
            return

        (vhl, self.tos, self.iplen, self.id, self.frag, self.ttl,
            self.protocol, self.csum, self.srcip, self.dstip) \
             = struct.unpack('!BBHHHBBHII', raw[:ipv4.MIN_LEN])

        self.v = vhl >> 4
        self.hl = vhl & 0x0f

        self.flags = self.frag >> 13
        self.frag  = self.frag & 0x1fff

        self.dstip = IPAddr(self.dstip)
        self.srcip = IPAddr(self.srcip)

        if self.v != ipv4.IPv4:
            self.msg('(ip parse) warning IP version %u not IPv4' % self.v)
            return
        elif self.hl < 5:
            self.msg('(ip parse) warning IP header %u longer than len %u' \
                        % (self.hl, self.iplen))
            return
        elif self.iplen < ipv4.MIN_LEN:
            self.msg('(ip parse) warning invalid IP len %u' % self.iplen)
            return
        elif (self.hl * 4) >= self.iplen or (self.hl * 4) > dlen:
            self.msg('(ip parse) warning IP header %u longer than len %u' \
                        % (self.hl, self.iplen))
            return

        # At this point, we are reasonably certain that we have an IP
        # packet
        self.parsed = True

        length = self.iplen
        if length > dlen:
            length = dlen # Clamp to what we've got
        if self.protocol == ipv4.UDP_PROTOCOL:
            self.next = udp(raw=raw[self.hl*4:length], prev=self)
        elif self.protocol == ipv4.TCP_PROTOCOL:
            self.next = tcp(raw=raw[self.hl*4:length], prev=self)
        elif self.protocol == ipv4.ICMP_PROTOCOL:
            self.next = icmp(raw=raw[self.hl*4:length], prev=self)
        elif self.protocol == ipv4.IGMP_PROTOCOL:
            self.next = igmp(raw=raw[self.hl*4:length], prev=self)
        elif dlen < self.iplen:
            self.msg('(ip parse) warning IP packet data shorter than IP len: %u < %u' % (dlen, self.iplen))
        else:
            self.next =  raw[self.hl*4:length]

        if isinstance(self.next, packet_base) and not self.next.parsed:
            self.next = raw[self.hl*4:length]
開發者ID:14gr1010,項目名稱:software,代碼行數:59,代碼來源:ipv4.py

示例4: getOutPortForIp

	def getOutPortForIp(self, switch, destIp):
		if DEBUG:
			print '*** _getOutPortForIp:'
			print switch, destIp
		dest = IPAddr(destIp)
		for entry in self.routingTable:
			if dest.inNetwork(entry.network) and \
						switch.name == entry.name:
				return entry.port	# port number
		return None
開發者ID:cannium,項目名稱:openflow_routing,代碼行數:10,代碼來源:pure.py

示例5: __contains__

 def __contains__ (self, item):
   item = IPAddr(item)
   if item in self.removed: return False
   n = item.toUnsigned()
   mask = (1<<self.host_size)-1
   nm = (n & mask) | self.network.toUnsigned()
   if nm != n: return False
   if (n & mask) == mask: return False
   if (n & mask) < self.first: return False
   if (n & mask) > self.last: return False
   return True
開發者ID:09beeihaq,項目名稱:Coursera-SDN-Assignments,代碼行數:11,代碼來源:dhcpd.py

示例6: MTDIPPrefix

class MTDIPPrefix(object):
    def __init__(self, pattern):
        parts = pattern.split("/")
        if len(parts) != 2:
            raise TypeError
        
        self.masklen = int(parts[1])
        self.pattern = IPAddr(parts[0])

        bits = bitarray()
        bits.frombytes(self.pattern.toRaw())
        self.prefix = bits[:self.masklen]

    def rand_ip_addr(self):
        rbitslen = 32 - self.masklen
        rbits = bin(random.getrandbits(rbitslen))[2:]
        return IPAddr((self.prefix + rbits.zfill(rbitslen)).tobytes())

    def __repr__(self):
        return "%s/%d" % (repr(self.pattern), self.masklen)

    def __contains__(self, ipaddr):
        if not isinstance(ipaddr, IPAddr):
            raise TypeError
        
        ipaddr_bits = bitarray()
        ipaddr_bits.frombytes(ipaddr.toRaw())

        return self.prefix == ipaddr_bits[:self.masklen]
開發者ID:ltanguay,項目名稱:NDS,代碼行數:29,代碼來源:pox_ctrl.py

示例7: __init__

 def __init__ (self, device = None, promiscuous = True, period = 10,
               start = True, callback = None, filter = None):
   if filter is not None:
     self.deferred_filter = (filter,)
   else:
     self.deferred_filter = None
   self.packets_received = 0
   self.packets_dropped = 0
   self._thread = None
   self.pcap = None
   self.promiscuous = promiscuous
   self.device = None
   self.period = period
   self.netmask = IPAddr("0.0.0.0")
   self._quitting = False
   self.addresses = {}
   if callback is None:
     self.callback = self.__class__._handle_rx
   else:
     self.callback = callback
   if device is not None:
     self.open(device)
   if self.pcap is not None:
     if start:
       self.start()
開發者ID:09beeihaq,項目名稱:pox,代碼行數:25,代碼來源:__init__.py

示例8: __init__

    def __init__(self, pattern):
        parts = pattern.split("/")
        if len(parts) != 2:
            raise TypeError
        
        self.masklen = int(parts[1])
        self.pattern = IPAddr(parts[0])

        bits = bitarray()
        bits.frombytes(self.pattern.toRaw())
        self.prefix = bits[:self.masklen]
開發者ID:ltanguay,項目名稱:NDS,代碼行數:11,代碼來源:pox_ctrl.py

示例9: ip

 def ip (self):
     ip = IPAddr("192.168.1.1")
     print str(ip)
     print ip.toUnsignedN() # converts to network-order unsigned integer 16885952
     print ip.toRaw() # returns a length-four bytes object 
     print "*****"
     ip = IPAddr(16885952, networkOrder=True)
     print str(ip)
開發者ID:anand3,項目名稱:PyTapDEMON,代碼行數:8,代碼來源:coreCompTest.py

示例10: __init__

    def __init__(
        self,
        device=None,
        promiscuous=True,
        period=10,
        start=True,
        callback=None,
        filter=None,
        use_bytearray=False,
        **kw
    ):
        """
    Initialize this instance

    use_bytearray: specifies capturing to bytearray buffers instead of bytes
    """

        if filter is not None:
            self.deferred_filter = (filter,)
        else:
            self.deferred_filter = None
        self.packets_received = 0
        self.packets_dropped = 0
        self._thread = None
        self.pcap = None
        self.promiscuous = promiscuous
        self.device = None
        self.use_bytearray = use_bytearray
        self.period = period
        self.netmask = IPAddr("0.0.0.0")
        self._quitting = False
        self.addresses = {}
        if callback is None:
            self.callback = self.__class__._handle_rx
        else:
            self.callback = callback

        for k, v in kw.items():
            assert not hasattr(self, k)
            setattr(self, k, v)

        if device is not None:
            self.open(device)
        if self.pcap is not None:
            if start:
                self.start()
開發者ID:bhushan99,項目名稱:Software-defined-networking,代碼行數:46,代碼來源:__init__.py

示例11: open

 def open(self, device, promiscuous=None, period=None, incoming=True, outgoing=False):
     assert self.device is None
     self.addresses = self.get_devices()[device]["addrs"]
     if "AF_INET" in self.addresses:
         self.netmask = self.addresses["AF_INET"].get("netmask")
         if self.netmask is None:
             self.netmask = IPAddr("0.0.0.0")
     # print "NM:",self.netmask
     # print self.addresses['AF_LINK']['addr']
     self.device = device
     if period is not None:
         self.period = period
     if promiscuous is not None:
         self.promiscuous = promiscuous
     self.pcap = pcapc.open_live(device, 65535, 1 if self.promiscuous else 0, self.period)
     pcapc.setdirection(self.pcap, incoming, outgoing)
     self.packets_received = 0
     self.packets_dropped = 0
     if self.deferred_filter is not None:
         self.set_filter(*self.deferred_filter)
         self.deferred_filter = None
開發者ID:bhushan99,項目名稱:Software-defined-networking,代碼行數:21,代碼來源:__init__.py

示例12: __init__

  def __init__ (self, network = "192.168.1.0/24", first = 2, last = None,
                count = None):
    """
    Simple subnet-based address pool

    Allocates count IP addresses out of network/network_size, starting
    with the first'th.  You may specify the end of the range with either
    last (to specify the last'th address to use) or count to specify the
    number to use.  If both are None, use up to the end of all
    legal addresses.

    Example for all of 192.168.x.x/16:
      SimpleAddressPool("192.168.0.0/16", 1, 65534)
    """
    network,network_size = parse_cidr(network)

    self.first = first
    self.network_size = network_size
    self.host_size = 32-network_size
    self.network = IPAddr(network)


    if last is None and count is None:
      self.last = (1 << self.host_size) - 2
    elif last is not None:
      self.last = last
    elif count is not None:
      self.last = self.first + count - 1
    else:
      raise RuntimeError("Cannot specify both last and count")

    self.removed = set()

    if self.count <= 0: raise RuntimeError("Bad first/last range")
    if first == 0: raise RuntimeError("Can't allocate 0th address")
    if self.host_size < 0 or self.host_size > 32:
      raise RuntimeError("Bad network")
    if IPAddr(self.last | self.network.toUnsigned()) not in self:
      raise RuntimeError("Bad first/last range")
開發者ID:hxnguyen,項目名稱:metaSDN,代碼行數:39,代碼來源:dhcpd.py

示例13: ipv4

class ipv4(packet_base):
    "IP packet struct"

    MIN_LEN = 20

    IPv4 = 4
    ICMP_PROTOCOL = 1
    TCP_PROTOCOL  = 6
    UDP_PROTOCOL  = 17
    IGMP_PROTOCOL = 2
    SINE_PROTOCOL = 160 #DJ++ 20131204 10100000


    DF_FLAG = 0x02
    MF_FLAG = 0x01

    ip_id = int(time.time())

    def __init__(self, raw=None, prev=None, **kw):
        packet_base.__init__(self)

        self.prev = prev

        self.v     = 4
        self.hl    = ipv4.MIN_LEN / 4
        self.tos   = 0
        self.iplen = ipv4.MIN_LEN
        ipv4.ip_id = (ipv4.ip_id + 1) & 0xffff
        self.id    = ipv4.ip_id
        self.flags = 0
        self.frag  = 0
        self.ttl   = 64
        self.protocol = 0
        self.csum  = 0
        self.srcip = IP_ANY
        self.dstip = IP_ANY
        self.next  = b''

        if raw is not None:
            self.parse(raw)

        self._init(kw) #for what? DJ 20131218

    def __str__(self):
        s = "[IP+%s %s>%s (cs:%02x v:%s hl:%s l:%s t:%s)]" % (
            ipproto_to_str(self.protocol),
            self.srcip, self.dstip,
            self.csum,
            self.v, self.hl, self.iplen, self.ttl)

        return s

    def parse(self, raw):
        assert isinstance(raw, bytes)
        self.raw = raw
        dlen = len(raw)
        if dlen < ipv4.MIN_LEN:
            self.msg('warning IP packet data too short to parse header: data len %u' % (dlen,))
            return

        (vhl, self.tos, self.iplen, self.id, self.frag, self.ttl,
            self.protocol, self.csum, self.srcip, self.dstip) \
             = struct.unpack('!BBHHHBBHII', raw[:ipv4.MIN_LEN])

        self.v = vhl >> 4
        self.hl = vhl & 0x0f

        self.flags = self.frag >> 13
        self.frag  = self.frag & 0x1fff

        if self.v != ipv4.IPv4:
            self.msg('(ip parse) warning IP version %u not IPv4' % self.v)
            return
        elif self.hl < 5:
            self.msg('(ip parse) warning IP header %u longer than len %u' \
                        % (self.hl, self.iplen))
            return
        elif self.iplen < ipv4.MIN_LEN:
            self.msg('(ip parse) warning invalid IP len %u' % self.iplen)
            return
        elif (self.hl * 4) >= self.iplen or (self.hl * 4) > dlen:
            self.msg('(ip parse) warning IP header %u longer than len %u' \
                        % (self.hl, self.iplen))
            return

        self.dstip = IPAddr(self.dstip)
        self.srcip = IPAddr(self.srcip)

        # At this point, we are reasonably certain that we have an IP
        # packet
        self.parsed = True

        length = self.iplen
        if length > dlen:
            length = dlen # Clamp to what we've got
        if self.protocol == ipv4.UDP_PROTOCOL:
            self.next = udp(raw=raw[self.hl*4:length], prev=self)
        elif self.protocol == ipv4.TCP_PROTOCOL:
            self.next = tcp(raw=raw[self.hl*4:length], prev=self)
        elif self.protocol == ipv4.ICMP_PROTOCOL:
#.........這裏部分代碼省略.........
開發者ID:TingOOOgniT,項目名稱:sine_controller,代碼行數:101,代碼來源:ipv4.py

示例14: SimpleAddressPool

class SimpleAddressPool (AddressPool):
  """
  Simple AddressPool for simple subnet based pools.
  """
  def __init__ (self, network = "192.168.0.0/24", first = 1, last = None,
                count = None):
    """
    Simple subnet-based address pool

    Allocates count IP addresses out of network/network_size, starting
    with the first'th.  You may specify the end of the range with either
    last (to specify the last'th address to use) or count to specify the
    number to use.  If both are None, use up to the end of all
    legal addresses.

    Example for all of 192.168.x.x/16:
      SimpleAddressPool("192.168.0.0/16", 1, 65534)
    """
    network,network_size = parse_cidr(network)

    self.first = first
    self.network_size = network_size
    self.host_size = 32-network_size
    self.network = IPAddr(network)

    if last is None and count is None:
      self.last = (1 << self.host_size) - 2
    elif last is not None:
      self.last = last
    elif count is not None:
      self.last = self.first + count - 1
    else:
      raise RuntimeError("Cannot specify both last and count")

    self.removed = set()

    if self.count <= 0: raise RuntimeError("Bad first/last range")
    if first == 0: raise RuntimeError("Can't allocate 0th address")
    if self.host_size < 0 or self.host_size > 32:
      raise RuntimeError("Bad network")
    if IPAddr(self.last | self.network.toUnsigned()) not in self:
      raise RuntimeError("Bad first/last range")

  def __repr__ (self):
    return str(self)

  def __str__ (self):
    t = self.network.toUnsigned()
    t = (IPAddr(t|self.first),IPAddr(t|self.last))
    return "<Addresses from %s to %s>" % t

  @property
  def subnet_mask (self):
    return IPAddr(((1<<self.network_size)-1) << self.host_size)

  @property
  def count (self):
    return self.last - self.first + 1

  def __contains__ (self, item):
    item = IPAddr(item)
    if item in self.removed: return False
    n = item.toUnsigned()
    mask = (1<<self.host_size)-1
    nm = (n & mask) | self.network.toUnsigned()
    if nm != n: return False
    if (n & mask) == mask: return False
    if (n & mask) < self.first: return False
    if (n & mask) > self.last: return False
    return True

  def append (self, item):
    item = IPAddr(item)
    if item not in self.removed:
      if item in self:
        raise RuntimeError("%s is already in this pool" % (item,))
      else:
        raise RuntimeError("%s does not belong in this pool" % (item,))
    self.removed.remove(item)

  def remove (self, item):
    item = IPAddr(item)
    if item not in self:
      raise RuntimeError("%s not in this pool" % (item,))
    self.removed.add(item)

  def __len__ (self):
    return (self.last-self.first+1) - len(self.removed)

  def __getitem__ (self, index):
    if index < 0:
      raise RuntimeError("Negative indices not allowed")
    if index >= len(self):
      raise IndexError("Item does not exist")
    c = self.first

    # Use a heuristic to find the first element faster (we hope)
    # Note this means that removing items changes the order of
    # our "list".
    c += len(self.removed)
#.........這裏部分代碼省略.........
開發者ID:09beeihaq,項目名稱:Coursera-SDN-Assignments,代碼行數:101,代碼來源:dhcpd.py

示例15: arp

class arp(packet_base):
    "ARP/RARP packet struct"

    MIN_LEN = 28

    HW_TYPE_ETHERNET = 1
    PROTO_TYPE_IP = 0x0800

    # OPCODES
    REQUEST = 1  # ARP
    REPLY = 2  # ARP
    REV_REQUEST = 3  # RARP
    REV_REPLY = 4  # RARP

    def __init__(self, raw=None, prev=None, **kw):
        packet_base.__init__(self)

        self.prev = prev

        self.hwtype = arp.HW_TYPE_ETHERNET
        self.prototype = arp.PROTO_TYPE_IP
        self.hwsrc = ETHER_ANY
        self.hwdst = ETHER_ANY
        self.hwlen = 6
        self.opcode = 0
        self.protolen = 4
        self.protosrc = IP_ANY
        self.protodst = IP_ANY
        self.next = b""

        if raw is not None:
            self.parse(raw)

        self._init(kw)

    def parse(self, raw):
        assert isinstance(raw, bytes)
        self.raw = raw
        dlen = len(raw)
        if dlen < arp.MIN_LEN:
            self.msg("(arp parse) warning IP packet data too short to parse header: data len %u" % dlen)
            return

        (self.hwtype, self.prototype, self.hwlen, self.protolen, self.opcode) = struct.unpack("!HHBBH", raw[:8])

        if self.hwtype != arp.HW_TYPE_ETHERNET:
            self.msg("(arp parse) hw type unknown %u" % self.hwtype)
        if self.hwlen != 6:
            self.msg("(arp parse) unknown hw len %u" % self.hwlen)
        else:
            self.hwsrc = EthAddr(raw[8:14])
            self.hwdst = EthAddr(raw[18:24])
        if self.prototype != arp.PROTO_TYPE_IP:
            self.msg("(arp parse) proto type unknown %u" % self.prototype)
        if self.protolen != 4:
            self.msg("(arp parse) unknown proto len %u" % self.protolen)
        else:
            self.protosrc = IPAddr(struct.unpack("!I", raw[14:18])[0])
            self.protodst = IPAddr(struct.unpack("!I", raw[24:28])[0])

        self.next = raw[28:]
        self.parsed = True

    def hdr(self, payload):
        buf = struct.pack("!HHBBH", self.hwtype, self.prototype, self.hwlen, self.protolen, self.opcode)
        if type(self.hwsrc) == bytes:
            buf += self.hwsrc
        else:
            buf += self.hwsrc.toRaw()
        if type(self.protosrc) is IPAddr:
            buf += struct.pack("!I", self.protosrc.toUnsigned())
        else:
            buf += struct.pack("!I", self.protosrc)
        if type(self.hwdst) == bytes:
            buf += self.hwdst
        else:
            buf += self.hwdst.toRaw()
        if type(self.protodst) is IPAddr:
            buf += struct.pack("!I", self.protodst.toUnsigned())
        else:
            buf += struct.pack("!I", self.protodst)
        return buf

    def __str__(self):
        op = str(self.opcode)

        eth_type = None
        # Ethernet
        if hasattr(self.prev, "type"):
            eth_type = self.prev.type
        # Vlan
        elif hasattr(self.prev, "eth_type"):
            eth_type = self.prev.eth_type
        else:
            self.err("(arp) unknown datalink type")
            eth_type = ethernet.ARP_TYPE

        if eth_type == ethernet.ARP_TYPE:
            if self.opcode == arp.REQUEST:
                op = "REQUEST"
#.........這裏部分代碼省略.........
開發者ID:XianliangJ,項目名稱:collections,代碼行數:101,代碼來源:arp.py


注:本文中的pox.lib.addresses.IPAddr類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。