From 3c68c43837f7db41c2272df973ef86857e8ada8b Mon Sep 17 00:00:00 2001 From: Bryan Davis Date: Wed, 10 Dec 2014 22:44:01 -0700 Subject: [PATCH] Cast input to IpRangeList Reduce the overhead of testing for membership in a long IpRangeList by ensuring that the provided input has been cast to an integer before checking each contained range. Closes #14 --- iptools/__init__.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/iptools/__init__.py b/iptools/__init__.py index 181f845..8d21ce9 100644 --- a/iptools/__init__.py +++ b/iptools/__init__.py @@ -249,7 +249,7 @@ def _cast(self, item): if ipv4 == self._ipver and item > ipv4.MAX_IP: # casting an ipv6 in an ipv4 range # downcast to ipv4 iff address is in the IPv4 mapped block - if item in IpRange(ipv6.IPV4_MAPPED): + if item in _IPV6_MAPPED_IPV4: item = item & ipv4.MAX_IP # end if @@ -395,6 +395,9 @@ def __iter__(self): # end class IpRange +_IPV6_MAPPED_IPV4 = IpRange(ipv6.IPV4_MAPPED) + + class IpRangeList (object): """ List of IpRange objects. @@ -464,6 +467,11 @@ def __contains__(self, item): :type item: str :returns: ``True`` if address is in list, ``False`` otherwise. """ + if isinstance(item, basestring): + item = _address2long(item) + if type(item) not in (type(1), type(ipv4.MAX_IP), type(ipv6.MAX_IP)): + raise TypeError( + "expected ip address, 32-bit integer or 128-bit integer") for r in self.ips: if item in r: return True