Python IPy.IP Examples

The following are 30 code examples of IPy.IP(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module IPy , or try the search function .
Example #1
Source File: ipdetails.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
def get_from_cached_prefix(self):
        """Search cache for existing cached Prefix"""
        details = None

        for cache_entry in cache.keys():
            if not cache_entry.decode().startswith("IPDetailsPrefix:"):
                continue

            prefix_details = cache.get(cache_entry)

            # data could exist but expired
            if not prefix_details:
                continue

            prefix = IPy.IP(prefix_details["Prefix"])

            if self.ip_object in prefix:
                details = prefix_details
                self.cached_prefix_found = True
                break

        return details 
Example #2
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 6 votes vote down vote up
def testIfComparesEqual(self):
        """nets of the same base and size should be considered equal, others not"""
        a = IPy.IP('127.0.0.0/24')
        a2 = a
        b = IPy.IP('127.0.0.0/24')
        c = IPy.IP('127.0.0.0/23')
        d = IPy.IP('127.0.0.0/22')
        e = IPy.IP('64.0.0.0/24')
        self.assertEqual(a2, a)
        self.assertEqual(a2, b)
        self.assertEqual(a, a)
        self.assertEqual(a, b)
        self.assertNotEqual(a, c)
        self.assertNotEqual(a, d)
        self.assertNotEqual(a, e)
        self.assertNotEqual(b, c)
        self.assertNotEqual(b, d)
        self.assertNotEqual(b, e)
        self.assertNotEqual(c, d)
        self.assertNotEqual(c, e)
        self.assertNotEqual(d, e) 
Example #3
Source File: ip_calc_utils.py    From g3ar with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def is_ipv4(ip):
    """Check if the [ip] is a real ip addr.
    
    Params:
        ip: :str: General IP format.
        
    Returns:
        :type: bool
        :desc: if ip is a valid IP addr, return true
            else return False"""
    try:
        IP(ip)
        return True
    except ValueError:
        return False

#---------------------------------------------------------------------- 
Example #4
Source File: munin-host.py    From munin with Apache License 2.0 6 votes vote down vote up
def is_pingable(ip):
    """
    Ping the target IP
    :param ip:
    :return:
    """
    try:
        # Ping parameters as function of OS
        ping_str = "-n 1 -w 500" if platform.system().lower() == "windows" else "-c 1 -W 500"
        # Ping
        subprocess.check_output("ping {0} {1}".format(ping_str, ip),
                                stderr=subprocess.STDOUT,
                                shell=True)
        return True
    except Exception as e:
        # traceback.print_exc()
        return False 
Example #5
Source File: verifyip.py    From N4xD0rk with GNU General Public License v3.0 6 votes vote down vote up
def VerifyIp(ip):

	ip_type = None

	try:

		ip_type = IP(ip).iptype()

		if ip_type is not "PUBLIC":

			ip_type = 'Private'

		else:

			ip_type = 'Public'

	except Exception:
		
		pass

	finally:

		return ip_type 
Example #6
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 6 votes vote down vote up
def testCheckPrefixOk(self):
        """Legal IP/prefix combinations should check ok."""
        self.assertTrue(IPy._checkPrefix(0x0, 32, 4))
        self.assertTrue(IPy._checkPrefix(0xffffffff, 32, 4))
        self.assertTrue(IPy._checkPrefix(0x7f000001, 32, 4))
        self.assertTrue(IPy._checkPrefix(0x80000000, 1, 4))
        self.assertTrue(IPy._checkPrefix(0x40000000, 2, 4))
        self.assertTrue(IPy._checkPrefix(0x80000000, 3, 4))
        self.assertTrue(IPy._checkPrefix(0x80000000, 4, 4))
        self.assertTrue(IPy._checkPrefix(0xffffff00, 24, 4))
        self.assertTrue(IPy._checkPrefix(0xffffff00, 24, 4))
        self.assertTrue(IPy._checkPrefix(0xfffffff0, 28, 4))
        self.assertTrue(IPy._checkPrefix(0x0, 32, 4))
        self.assertTrue(IPy._checkPrefix(0x0, 1, 4))
        self.assertTrue(IPy._checkPrefix(0x0, 0, 4))
        self.assertTrue(IPy._checkPrefix(0xffffffffffffffff0000000000000000, 64, 6))
        self.assertTrue(IPy._checkPrefix(0x0, 64, 6))
        self.assertTrue(IPy._checkPrefix(0x0, 0, 6))
        self.assertTrue(IPy._checkPrefix(0x0, 128, 6))
        self.assertTrue(IPy._checkPrefix(0xffffffffffffffffffffffffffffffff, 128, 6)) 
Example #7
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 6 votes vote down vote up
def testStrBin(self):
        """Binary string Output."""

        testValues = [('0.0.0.0', '00000000000000000000000000000000'),
                      ('0.0.0.1', '00000000000000000000000000000001'),
                      ('255.255.255.255', '11111111111111111111111111111111'),
                      ('128.0.0.0', '10000000000000000000000000000000'),
                      ('::0', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'),
                      ('::1', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001'),
                      ('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'),
                      ('5555:5555:5555:5555:5555:5555:5555:5555', '01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101'),
                      ('aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa', '10101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010'),
                      ('85.85.85.85', '01010101010101010101010101010101'),
                      ('170.170.170.170', '10101010101010101010101010101010'),
                      ('127.0.0.1', '01111111000000000000000000000001'),
                      ('1::2:0:0:3', '00000000000000010000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000011')]
        for (question, answer) in testValues:
            result = IPy.IP(question).strBin()
            self.assertEqual(answer, result, (question, answer, result)) 
Example #8
Source File: vt-checker-hosts.py    From Loki with GNU General Public License v3.0 6 votes vote down vote up
def is_pingable(ip):
    """
    Ping the target IP
    :param ip:
    :return:
    """
    try:
        # Ping parameters as function of OS
        ping_str = "-n 1 -w 500" if platform.system().lower() == "windows" else "-c 1 -W 500"
        # Ping
        subprocess.check_output("ping {0} {1}".format(ping_str, ip),
                                stderr=subprocess.STDOUT,
                                shell=True)
        return True
    except Exception, e:
        # traceback.print_exc()
        return False 
Example #9
Source File: port_prober.py    From platform with GNU General Public License v3.0 6 votes vote down vote up
def probe_port(self, port, protocol, ip):
        self.logger.info('probing {0}'.format(port))
        url = urljoin(self.redirect_api_url, "/probe/port_v2")
        try:
            request = {'token': self.update_token, 'port': port, 'protocol': protocol}
            if ip:
                iptype=IP(ip).iptype()
                if iptype != 'PUBLIC':
                    return False, 'IP: {0} is not public'.format(ip)
                request['ip'] = ip

            response = requests.get(url, params=request)
            self.logger.info('response status_code: {0}'.format(response.status_code))
            self.logger.info('response text: {0}'.format(response.text))
            result = json.loads(response.text)
            if response.status_code == 200 and result['message'] == 'OK':
                return True, ''
            else:
                external_device_ip = result['device_ip']
                ip_version = IP(external_device_ip).version()
                return False, 'using device public IP: "{0}" which is IPv{1}'.format(external_device_ip, ip_version)
                    
        except Exception as e:
            self.logger.info('{0} is not reachable, error: {1}'.format(port, str(e)))
            return False, 'unable to validate external port: {0}'.format(str(e)) 
Example #10
Source File: ipdetails.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, address):
        self.cached_prefix_found = False
        self.ip_object = IPy.IP(address)

        self.address = self.ip_object.strFullsize()
        self.asn = None
        self.holder = None
        self.prefix = None
        self.not_querable_types = [
            'RESERVED', 'UNSPECIFIED', 'LOOPBACK',
            'UNASSIGNED', 'DOCUMENTATION', 'ULA',
            'LINKLOCAL', 'PRIVATE'
        ]

        details = self._get_details()
        if details:
            self.asn = details["ASN"]
            self.holder = details["Holder"]
            self.prefix = details["Prefix"] 
Example #11
Source File: vt-checker-hosts.py    From Loki with GNU General Public License v3.0 5 votes vote down vote up
def process_lines(lines, debug=False):
    """
    Process the input file line by line
    """
    # Counter
    linenr = 0
    # Elements
    elements = []

    # Loop through lines -----------------------------------------------------------------------------------------------
    for line in lines:
        # Skip comments
        if line.startswith("#"):
            continue

        ips, domains = fetch_ip_and_domains(line)
        if debug:
            if len(ips):
                print "[D] IPs: {0}".format(', '.join(ips))
            if len(domains):
                print "[D] Domains: {0}".format(', '.join(domains))

        # Line number
        linenr += 1

        # If no IP or Domain found in line
        if len(ips) < 1 and len(domains) < 1:
            continue

        # Elements
        for i in ips:
            elements.append({"value": i, "type": "ip"})
        for h in domains:
            elements.append({"value": h, "type": "domain"})

    return elements 
Example #12
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 5 votes vote down vote up
def testStrCompressed(self):
        """Compressed string Output."""
        testValues = ['127.0.0.1',
                  'dead::beef',
                  'dead:beef::',
                  'dead:beef::/48',
                  'ff00:1::',
                  'ff00:0:f000::',
                  '0:0:1000::',
                  '::e000:0/112',
                  '::e001:0/112',
                  'dead:beef::/48',
                  'ff00:1::/64',
                  'ff00:0:f000::/64',
                  '0:0:1000::/64',
                  '::e000:0/112',
                  '::e001:0/112',
                  '::1:0:0:0:2',
                  '0:1:2:3:4:5:6:7',
                  '1:2:3:4:0:5:6:7',
                  '1:2:3:4:5:6:7:0',
                  '1:0:0:2::',
                  '1:0:0:2::3',
                  '1::2:0:0:3']
        for question in testValues:
            result = IPy.IP(question).strCompressed()
            self.assertEqual(question, result, (question, result)) 
Example #13
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 5 votes vote down vote up
def testStrFullsize(self):
        """Normal / 0-padded string Output."""
        testValues = [(338770000845734292534325025077361652240, 'fedc:ba98:7654:3210:fedc:ba98:7654:3210'),
                      (21932261930451111902915077091070067066, '1080:0000:0000:0000:0008:0800:200c:417a'),
                      (338958331222012082418099330867817087043, 'ff01:0000:0000:0000:0000:0000:0000:0043'),
                      (0, '0.0.0.0'),
                      (2130706433, '127.0.0.1'),
                      (4294967295, '255.255.255.255'),
                      (1, '0.0.0.1'),
                      (3588059479, '213.221.113.87')]
        for (question, answer) in testValues:
            result = IPy.IP(question).strFullsize(question)
            self.assertEqual(answer, result, (question, result, answer)) 
Example #14
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 5 votes vote down vote up
def testStrNormal(self):
        """Normal string Output."""
        testValues = [(338770000845734292534325025077361652240, 'fedc:ba98:7654:3210:fedc:ba98:7654:3210'),
                      (21932261930451111902915077091070067066, '1080:0:0:0:8:800:200c:417a'),
                      (338958331222012082418099330867817087043, 'ff01:0:0:0:0:0:0:43'),
                      (0, '0.0.0.0'),
                      (2130706433, '127.0.0.1'),
                      (4294967295, '255.255.255.255'),
                      (1, '0.0.0.1'),
                      (3588059479, '213.221.113.87')]
        for (question, answer) in testValues:
            result = IPy.IP(question).strNormal(question)
            self.assertEqual(answer, result, (question, result, answer)) 
Example #15
Source File: vt-checker-hosts.py    From Loki with GNU General Public License v3.0 5 votes vote down vote up
def is_private(ip):
    ip = IP(ip)
    if ip.iptype() == "PRIVATE":
        return True
    return False 
Example #16
Source File: common.py    From WatchAD with GNU General Public License v3.0 5 votes vote down vote up
def ip_filter(ip) -> bool:
    if ip == "-" or ip == "::1":
        return True
    try:
        ip = IP(ip)
    except Exception as e:
        return True
    if ip in IP("127.0.0.0/8"):
        return True
    if ip.iptype() not in ["PRIVATE", "PUBLIC"]:
        return True 
Example #17
Source File: dnssearch.py    From kalel with GNU General Public License v3.0 5 votes vote down vote up
def get_ip_list(self, ips):
        """Generates the list of ips to reverse"""
        try:
            list = IPy.IP(ips)
        except:
            print "Error in IP format, check the input and try again. (Eg. 192.168.1.0/24)"
            sys.exit()
        name = []
        for x in list:
            name.append(str(x))
        return name 
Example #18
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 5 votes vote down vote up
def testStrDec(self):
        """Decimal string Output."""
        testValues = [(338770000845734292534325025077361652240, '338770000845734292534325025077361652240'),
                      (21932261930451111902915077091070067066, '21932261930451111902915077091070067066'),
                      (338958331222012082418099330867817087043, '338958331222012082418099330867817087043'),
                      (0, '0'),
                      (1, '1'),
                      (0xFFFFFFFF, '4294967295'),
                      (0xD5DD7157, '3588059479')]
        for (question, answer) in testValues:
            result = IPy.IP(question).strDec(question)
            self.assertEqual(answer, result, (question, result, answer)) 
Example #19
Source File: dnssearch-threads.py    From kalel with GNU General Public License v3.0 5 votes vote down vote up
def get_ip_list(self, ips):
        """Generates the list of ips to reverse"""
        try:
            list = IPy.IP(ips)
        except:
            print "Error in IP format, check the input and try again. (Eg. 192.168.1.0/24)"
            sys.exit()
        name = []
        for x in list:
            name.append(str(x))
        return name 
Example #20
Source File: server.py    From PRCDNS with The Unlicense 5 votes vote down vote up
def get_arg():
    """解析参数"""
    parser = argparse.ArgumentParser(prog='prcdns', description='google dns proxy.')
    parser.add_argument('--debug', help='debug model,default NO', default=False)
    parser.add_argument('-l', '--listen', help='listening IP,default 0.0.0.0', default='0.0.0.0')
    parser.add_argument('-p', '--port', help='listening Port,default 3535', default=3535)
    parser.add_argument('-r', '--proxy', help='Used For Query Google DNS,default direct', default=None)
    parser.add_argument('-ip', '--myip', help='IP location', default=None)

    return parser.parse_args() 
Example #21
Source File: server.py    From PRCDNS with The Unlicense 5 votes vote down vote up
def data_received(self, data):
        data = self.get_data(data)
        if data is None:
            self.transport.close()
            return
        self.request = DNSRecord.parse(data)
        if self.args.debug:
            print('Data received: {!r}'.format(self.request))

        from IPy import IP
        ip = IP(self.peername[0])
        client_ip = self.peername[0]
        if ip.iptype() == 'PRIVATE':
            client_ip = self.args.myip

        url = 'https://dns.google.com/resolve?name={}&edns_client_subnet={}/24'.format(str(self.request.q.qname),
                                                                                       client_ip)
        # client = ProxyClient()
        # google_dns_resp = client.query_domain(url, self.args.proxy)
        try:
            from asyncio import ensure_future
        except ImportError:
            from asyncio import async as ensure_future

        asyncio.ensure_future(ProxyClient.query_domain(url, self.args.proxy), loop=self.loop).add_done_callback(
            functools.partial(self.send_resp)) 
Example #22
Source File: validators.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def validate_address_or_network(value):
    try:
        IPy.IP(value)
    except ValueError:
        raise ValidationError('"%s" is not a valid ip address or network address' % value) 
Example #23
Source File: models.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def contain(self, elt):
        if elt.threshold_type != self.threshold_type:
            return False
        if elt.track_by != self.track_by:
            return False
        if elt.threshold_type == 'suppress':
            if not IPy.IP(self.net).overlaps(IPy.IP(elt.net)):
                return False
        return True 
Example #24
Source File: models.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def build_sigs_group(self):
        # query sigs with group set
        rules = Rule.objects.filter(group = True, category = self)
        sigs_groups = {}
        # build hash on message
        for rule in rules:
            # let's get the new IP only, will output that as text field at save time
            rule.ips_list = set()
            sigs_groups[rule.msg] = rule
        return sigs_groups 
Example #25
Source File: models.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def _apply_target_trans(self, rule_ids):
        terms = re.split(r' +', rule_ids.format())
        src = terms[2]
        dst = terms[5]

        if self._test_scan_rules(rule_ids):
            self._set_target(rule_ids, target="dest_ip")
        # external net always seen as bad guy on attack if not OUTBOUND
        elif src == "$EXTERNAL_NET":
            self._set_target(rule_ids, target="dest_ip")

        # external net always seen as bad guy on attack
        elif dst == "$EXTERNAL_NET":
            self._set_target(rule_ids, target="src_ip")

        # any or IP address list on one side and a variable on other side implies variable is our asset so target
        elif (src == "any" or src.startswith("[")) and dst.startswith("$"):
            self._set_target(rule_ids, target="dest_ip")

        # any or IP address list on one side and a variable on other side implies variable is our asset so target
        elif src.startswith("$") and (dst == "any" or dst.startswith("[")):
            self._set_target(rule_ids, target="src_ip")

        elif rule_ids.sid in [2017060, 2023070, 2023071, 2023549, 2024297, 2023548, 2024435, 2023149]:
            self._set_target(rule_ids, target="dest_ip")

        elif rule_ids.sid in []:
            self._set_target(rule_ids, target="src_ip") 
Example #26
Source File: models.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def validate_hostname(val):
    try:
        validate_ipv4_address(val)
    except ValidationError:
        # ip may in fact be a hostname
        # http://www.regextester.com/23
        HOSTNAME_RX = r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$'
        if not re.match(HOSTNAME_RX, val):
            raise ValidationError('Invalid hostname or IP') 
Example #27
Source File: rest_processing.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def validate(self, data):
        if data['key'] in self.IP_FIELDS:
            try:
                addr = IP(data['value'])
                if data['operator'] == 'contains' and len(addr) == 1:
                    raise ValueError('not a network address')
            except ValueError:
                _type = 'IP'
                if data['operator'] == 'contains':
                    _type = 'network'
                raise serializers.ValidationError({'value': ['This field requires a valid %s address.' % _type]})
        return data 
Example #28
Source File: dnssearch.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_ip_list(self,ips):
		"""Generates the list of ips to reverse"""
		try:
			list=IPy.IP(ips)
		except:
			print "Error in IP format, check the input and try again. (Eg. 192.168.1.0/24)"
			sys.exit()
		name=[]
		for x in list:
			name.append(str(x))
		return name 
Example #29
Source File: dnssearch-threads.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_ip_list(self,ips):
		"""Generates the list of ips to reverse"""
		try:
			list=IPy.IP(ips)
		except:
			print "Error in IP format, check the input and try again. (Eg. 192.168.1.0/24)"
			sys.exit()
		name=[]
		for x in list:
			name.append(str(x))
		return name 
Example #30
Source File: test_IPy.py    From dirmap with GNU General Public License v3.0 5 votes vote down vote up
def testNetmask(self):
        """Netmask should return netmasks"""
        self.assertEqual(str(IPy.IP("0.0.0.0/0").netmask()), "0.0.0.0")
        self.assertEqual(str(IPy.IP("0.0.0.0/32").netmask()), "255.255.255.255")
        self.assertEqual(str(IPy.IP("127.0.0.0/24").netmask()), "255.255.255.0")
        self.assertEqual(str(IPy.IP("2001:1234:5678:1234::/64").netmask()), "ffff:ffff:ffff:ffff:0000:0000:0000:0000")