Python ipaddr.IPAddress() Examples
The following are 30
code examples of ipaddr.IPAddress().
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
ipaddr
, or try the search function
.
Example #1
Source File: _net.py From flocker with Apache License 2.0 | 7 votes |
def get_all_ips(): """ Find all IPs for this machine. :return: ``set`` of IP addresses (``IPAddress``). """ ips = set() interfaces = netifaces.interfaces() for interface in interfaces: addresses = netifaces.ifaddresses(interface) for address_family in (netifaces.AF_INET, netifaces.AF_INET6): family_addresses = addresses.get(address_family) if not family_addresses: continue for address in family_addresses: ips.add(ipaddress_from_string(address['addr'])) return ips
Example #2
Source File: _client.py From flocker with Apache License 2.0 | 6 votes |
def list_nodes(self): request = self._request( b"GET", b"/state/nodes", None, {OK} ) def to_nodes(result): """ Turn the list of dicts into ``Node`` instances. """ nodes = [] for node_dict in result: node = Node( uuid=UUID(hex=node_dict['uuid'], version=4), public_address=IPAddress(node_dict['host']), ) nodes.append(node) return nodes request.addCallback(to_nodes) return request
Example #3
Source File: __init__.py From rtapi with GNU General Public License v2.0 | 6 votes |
def SetIP6Comment(self, comment, ip): """ Set comment for IPv6 address """ # Create address object using ipaddr addr6 = ipaddr.IPAddress(ip) # Create IPv6 format for Mysql db_ip6_format = "".join(str(x) for x in addr6.exploded.split(':')).upper() sql = "SELECT comment FROM IPv6Address WHERE HEX(ip) = '%s'" % (db_ip6_format) result = self.db_query_one(sql) if result is not None: sql = "UPDATE IPv6Address SET comment = '%s' WHERE HEX(ip) = '%s'" % (comment, db_ip6_format) else: sql = "INSERT INTO IPv6Address (ip, comment) VALUES (UNHEX('%s'), '%s')" % (db_ip6_format, comment) self.db_insert(sql)
Example #4
Source File: test_cputime.py From flocker with Apache License 2.0 | 6 votes |
def test_get_node_cpu_times(self): """ Success results in output of dictionary containing process names. """ d = get_node_cpu_times( Clock(), _LocalRunner(), Node(uuid=uuid4(), public_address=IPAddress('10.0.0.1')), _pid_1_name, [_pid_1_name], ) def check(result): self.assertEqual( set(result.keys()), {_pid_1_name, WALLCLOCK_LABEL} ) d.addCallback(check) return d
Example #5
Source File: test_create_dataset.py From flocker with Apache License 2.0 | 6 votes |
def test_empty_cluster(self): """ CreateDataset fails if no nodes in cluster. """ control_service = FakeFlockerClient() cluster = BenchmarkCluster( IPAddress('10.0.0.1'), lambda reactor: control_service, {}, None, ) d = CreateDataset(Clock(), cluster).get_probe() self.failureResultOf(d, EmptyClusterError)
Example #6
Source File: test_read_request_load.py From flocker with Apache License 2.0 | 6 votes |
def test_scenario_throws_exception_when_already_started(self, _logger): """ start method in the ``RequestLoadScenario`` throws a ``RequestScenarioAlreadyStarted`` if the scenario is already started. """ c = Clock() node1 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.1')) node2 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.2')) cluster = BenchmarkCluster( node1.public_address, lambda reactor: FakeFlockerClient([node1, node2]), {node1.public_address, node2.public_address}, default_volume_size=DEFAULT_VOLUME_SIZE ) sample_size = 5 s = read_request_load_scenario(c, cluster, sample_size=sample_size) s.start() self.assertRaises(RequestScenarioAlreadyStarted, s.start)
Example #7
Source File: ip_utils.py From st2 with Apache License 2.0 | 5 votes |
def is_ipv6(ip_str): """ Validate whether given string is IPv6. :param ip_str: String to validate. :type ip_str: ``str`` :rtype: ``bool`` """ try: addr = ipaddr.IPAddress(ip_str) return addr.version == 6 except: return False
Example #8
Source File: _net.py From flocker with Apache License 2.0 | 5 votes |
def ipaddress_from_string(ip_address_string): """ Parse an IPv4 or IPv6 address string and return an IPAddress instance. Remove the "embedded scope id" from IPv6 addresses (if there is one). :param str ip_address_string: The IP address string to be parsed. :returns: An ``ipaddr.IPAddress`` instance. """ # There may be an embedded scope id in an IPv6 address. Discard # it. Eg fe80::f816:3eff:fe11:ca54%eth0 parts = ip_address_string.rsplit('%', 1) ip_address_string = parts[0] return IPAddress(ip_address_string)
Example #9
Source File: common.py From dnsAutoRebinding with GNU General Public License v3.0 | 5 votes |
def analy_req(address): mainDomain = conf_read('maindomain') address = address[:-len(mainDomain) - 1] payload = conf_read('payload') encoding = conf_read('encoding') record = address try: if encoding == 'int': record = ipaddr.IPAddress(int(address)).__str__() elif encoding == 'hex': try: address = address.decode('hex') if ipaddr.IPAddress(address).version == 4: record = address elif conf_read('type') == 'AAAA' and ipaddr.IPAddress(address).version == 6: record = address else: pass except: pass # elif False not in map(lambda x:x in map(lambda x:chr(x),range(97,108)),list(address)): elif encoding == 'en': record = numToEnToNum(address) elif payload != 'None' and payload.find(mainDomain) == -1: # record = payload + "www.google.com" record = payload + mainDomain except Exception,e: print '[!] Subdomain Invalid {}'.format(e)
Example #10
Source File: common.py From dnsAutoRebinding with GNU General Public License v3.0 | 5 votes |
def ipListBuild(address): print '1. Single IP Covert For En\n2. Build IP List' opt_req = raw_input("[+] [1 By Default/2]") or '1' if opt_req == '1': print numToEnToNum(address) exit() conf_main = conf_read('maindomain')[:-1] seg_len = raw_input("[+] Please Input Segment Length [24 By Default]") or 24 encode_req = raw_input("[+] Please Input Encoding ['ipv4' By Default]") mainDomain = raw_input("[+] Please Input Server Root Address [{} By Default]".format(conf_main)) or conf_main segment = eval("ipaddr.IPv4Network('{}/{}').iterhosts()".format(address, int(seg_len))) save_file = "{}_{}_{}.txt".format(time.strftime("%Y%m%d%X", time.localtime()).replace(':', ''), mainDomain.replace('.','_'),(encode_req if encode_req else 'ipv4')) results = [] try: if encode_req == '': results += ["{}.{}".format(str(i),mainDomain) for i in list(segment)] elif encode_req == 'en': results += ["{}.{}".format(numToEnToNum(str(i)),mainDomain) for i in list(segment)] elif encode_req == 'int': results += ["{}.{}".format(int(ipaddr.IPAddress(str(i))),mainDomain) for i in list(segment)] elif encode_req == 'hex': results += ["{}.{}".format(str(i).encode('hex'),mainDomain) for i in list(segment)] else: pass f = open(save_file,'a') [f.write(i+'\n') for i in results] f.close() print '[+] Stored in the {}'.format(save_file) except Exception,e: print e exit()
Example #11
Source File: acehttp.py From HTTPAceProxy with GNU General Public License v3.0 | 5 votes |
def checkFirewall(clientip): try: clientinrange = any([IPAddress(clientip) in IPNetwork(i) for i in AceConfig.firewallnetranges]) except: logger.error('Check firewall netranges settings !'); return False return not ((AceConfig.firewallblacklistmode and clientinrange) or (not AceConfig.firewallblacklistmode and not clientinrange))
Example #12
Source File: spf.py From mailin with MIT License | 5 votes |
def set_ip(self, i): "Set connect ip, and ip6 or ip4 mode." self.iplist = False if i.lower() == 'list': self.iplist = [] ip6 = False elif i.lower() == 'list6': self.iplist = [] ip6 = True else: try: self.ipaddr = ipaddress.ip_address(i) except AttributeError: self.ipaddr = ipaddress.IPAddress(i) if self.ipaddr.version == 6: if self.ipaddr.ipv4_mapped: self.ipaddr = ipaddress.IPv4Address(self.ipaddr.ipv4_mapped) ip6 = False else: ip6 = True else: ip6 = False self.c = str(self.ipaddr) # NOTE: self.A is not lowercase, so isn't a macro. See query.expand() if ip6: self.A = 'AAAA' self.v = 'ip6' self.i = '.'.join(list(self.ipaddr.exploded.replace(':','').upper())) self.cidrmax = 128 else: self.A = 'A' self.v = 'in-addr' self.i = self.ipaddr.exploded self.cidrmax = 32
Example #13
Source File: http_server.py From rekall with GNU General Public License v2.0 | 5 votes |
def __init__(self, server_address, handler, *args, **kwargs): self.session = kwargs.pop("session") (address, _) = server_address version = ipaddr.IPAddress(address).version if version == 4: self.address_family = socket.AF_INET elif version == 6: self.address_family = socket.AF_INET6 http.server.HTTPServer.__init__( self, server_address, handler, *args, **kwargs)
Example #14
Source File: ip_utils.py From st2 with Apache License 2.0 | 5 votes |
def is_ipv4(ip_str): """ Validate whether given string is IPv4. :param ip_str: String to validate. :type ip_str: ``str`` :rtype: ``bool`` """ try: addr = ipaddr.IPAddress(ip_str) return addr.version == 4 except: return False
Example #15
Source File: __init__.py From rtapi with GNU General Public License v2.0 | 5 votes |
def InterfaceAddIpv6IP(self, object_id, device, ip): """Add/Update IPv6 IP on interface""" # Create address object using ipaddr addr6 = ipaddr.IPAddress(ip) # Create IPv6 format for Mysql ip6 = "".join(str(x) for x in addr6.exploded.split(':')).upper() sql = "SELECT HEX(ip) FROM IPv6Allocation WHERE object_id = %d AND name = '%s'" % (object_id, device) result = self.db_query_all(sql) if result is not None: old_ips = result is_there = "no" for old_ip in old_ips: if old_ip[0] == ip6: is_there = "yes" if is_there == "no": sql = "SELECT name FROM IPv6Allocation WHERE object_id = %d AND ip = UNHEX('%s')" % (object_id, ip6) result = self.db_query_all(sql) if result is not None: if result != (): sql = "DELETE FROM IPv6Allocation WHERE object_id = %d AND ip = UNHEX('%s')" % (object_id, ip6) self.db_insert(sql) self.InsertLog(object_id, "Removed IP (%s) from interface %s" % (ip, result[0][0])) sql = "INSERT INTO IPv6Allocation (object_id,ip,name) VALUES (%d,UNHEX('%s'),'%s')" % (object_id, ip6, device) self.db_insert(sql) text = "Added IPv6 IP %s on %s" % (ip, device) self.InsertLog(object_id, text)
Example #16
Source File: __init__.py From rtapi with GNU General Public License v2.0 | 5 votes |
def CleanIPv6Addresses(self, object_id, ip_addresses, device): """Clean unused ipv6 from object. ip_addresses mus be list of active IP addresses on device (device) on host (object_id)""" sql = "SELECT HEX(ip) FROM IPv6Allocation WHERE object_id = %d AND name = '%s'" % (object_id, device) result = self.db_query_all(sql) if result is not None: old_ips = result delete_ips = [] new_ip6_ips = [] # We must prepare ipv6 addresses into same format for compare for new_ip in ip_addresses: converted = ipaddr.IPAddress(new_ip).exploded.lower() new_ip6_ips.append(converted) for old_ip_hex in old_ips: try: # First we must construct IP from HEX tmp = re.sub("(.{4})", "\\1:", old_ip_hex[0], re.DOTALL) # Remove last : and lower string old_ip = tmp[:len(tmp) - 1].lower() test = new_ip6_ips.index(old_ip) except ValueError: delete_ips.append(old_ip) if len(delete_ips) != 0: for ip in delete_ips: db_ip6_format = "".join(str(x) for x in ip.split(':')) sql = "DELETE FROM IPv6Allocation WHERE ip = UNHEX('%s') AND object_id = %d AND name = '%s'" % (db_ip6_format, object_id, device) self.db_insert(sql) logstring = "Removed IP %s from %s" % (ip, device) self.InsertLog(object_id, logstring)
Example #17
Source File: iputils.py From flare with MIT License | 5 votes |
def private_check(ip): return ip_addr(ip).is_private
Example #18
Source File: iputils.py From flare with MIT License | 5 votes |
def multicast_check(ip): return ip_addr(ip).is_multicast
Example #19
Source File: iputils.py From flare with MIT License | 5 votes |
def reserved_check(ip): return ip_addr(ip).is_reserved
Example #20
Source File: ssh.py From flocker with Apache License 2.0 | 5 votes |
def __init__(self, base_path): """ :param FilePath base_path: The path beneath which all of the temporary SSH server-related files will be created. An ``ssh`` directory will be created as a child of this directory to hold the key pair that is generated. An ``sshd`` directory will also be created here to hold the generated host key. A ``home`` directory is also created here and used as the home directory for shell logins to the server. """ self.home = base_path.child(b"home") self.home.makedirs() ssh_path = base_path.child(b"ssh") ssh_path.makedirs() self.key_path = ssh_path.child(b"key") key = generate_ssh_key(self.key_path) sshd_path = base_path.child(b"sshd") sshd_path.makedirs() self.host_key_path = sshd_path.child(b"ssh_host_key") generate_ssh_key(self.host_key_path) factory = OpenSSHFactory() realm = _UnixSSHRealm(self.home) checker = _InMemoryPublicKeyChecker(public_key=key.public()) factory.portal = Portal(realm, [checker]) factory.dataRoot = sshd_path.path factory.moduliRoot = b"/etc/ssh" self._port = reactor.listenTCP(0, factory, interface=b"127.0.0.1") self.ip = IPAddress(self._port.getHost().host) self.port = self._port.getHost().port
Example #21
Source File: test_create_container.py From flocker with Apache License 2.0 | 5 votes |
def test_run_probe_timeout(self): """ CreateContainer probe times-out if probe.run runs too long. """ clock = Clock() node_id = uuid4() node = Node(uuid=node_id, public_address=IPAddress('10.0.0.1')) control_service = FakeFlockerClient([node], node_id) cluster = BenchmarkCluster( IPAddress('10.0.0.1'), lambda reactor: control_service, {}, None, ) operation = CreateContainer(clock, cluster) d = operation.get_probe() control_service.synchronize_state() # creation of pull container clock.advance(1) control_service.synchronize_state() # deletion of pull container clock.advance(1) # get_probe has completed successfully probe = self.successResultOf(d) d = probe.run() clock.advance(DEFAULT_TIMEOUT.total_seconds()) # No control_service.synchronize_state() call, so cluster state # never shows container is created. # The Deferred fails if container not created within 10 minutes. self.failureResultOf(d)
Example #22
Source File: test_create_container.py From flocker with Apache License 2.0 | 5 votes |
def test_get_probe_timeout(self): """ CreateContainer probe times-out if get_probe runs too long. """ clock = Clock() node_id = uuid4() node = Node(uuid=node_id, public_address=IPAddress('10.0.0.1')) control_service = FakeFlockerClient([node], node_id) cluster = BenchmarkCluster( IPAddress('10.0.0.1'), lambda reactor: control_service, {}, None, ) operation = CreateContainer(clock, cluster) d = operation.get_probe() clock.advance(DEFAULT_TIMEOUT.total_seconds()) # No control_service.synchronize_state() call, so cluster state # never shows container is created. # The Deferred fails if container not created within 10 minutes. self.failureResultOf(d)
Example #23
Source File: vlan.py From iSDX with Apache License 2.0 | 5 votes |
def __init__(self, vid, conf=None): if conf is None: conf = {} self.vid = vid self.tagged = [] self.untagged = [] self.name = conf.setdefault('name', str(vid)) self.description = conf.setdefault('description', self.name) self.controller_ips = conf.setdefault('controller_ips', []) if self.controller_ips: self.controller_ips = [ ipaddr.IPNetwork(ip) for ip in self.controller_ips] self.unicast_flood = conf.setdefault('unicast_flood', True) self.routes = conf.setdefault('routes', {}) self.ipv4_routes = {} self.ipv6_routes = {} if self.routes: self.routes = [route['route'] for route in self.routes] for route in self.routes: ip_gw = ipaddr.IPAddress(route['ip_gw']) ip_dst = ipaddr.IPNetwork(route['ip_dst']) assert(ip_gw.version == ip_dst.version) if ip_gw.version == 4: self.ipv4_routes[ip_dst] = ip_gw else: self.ipv6_routes[ip_dst] = ip_gw self.arp_cache = {} self.nd_cache = {} self.max_hosts = conf.setdefault('max_hosts', None) self.host_cache = {}
Example #24
Source File: test_create_dataset.py From flocker with Apache License 2.0 | 5 votes |
def test_create_dataset(self, logger): """ CreateDataset probe waits for cluster to converge. """ clock = Clock() node_id = uuid4() node = Node(uuid=node_id, public_address=IPAddress('10.0.0.1')) control_service = FakeFlockerClient([node], node_id) cluster = BenchmarkCluster( IPAddress('10.0.0.1'), lambda reactor: control_service, {}, None, ) operation = CreateDataset(clock, cluster) d = operation.get_probe() def run_probe(probe): def cleanup(result): cleaned_up = probe.cleanup() cleaned_up.addCallback(lambda _ignored: result) return cleaned_up d = probe.run() d.addCallback(cleanup) return d d.addCallback(run_probe) # Advance the clock because probe periodically polls the state. # The Deferred does not fire before the dataset has been created. clock.advance(1) self.assertNoResult(d) # Trigger convergence of the fake Flocker cluster. control_service.synchronize_state() # The Deferred fires once the dataset has been created. clock.advance(1) self.successResultOf(d)
Example #25
Source File: test_read_request_load.py From flocker with Apache License 2.0 | 5 votes |
def test_read_request_load_start_stop_start_succeeds(self, _logger): """ ``read_request_load_scenario`` starts, stops and starts without collapsing. """ c = Clock() node1 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.1')) node2 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.2')) cluster = BenchmarkCluster( node1.public_address, lambda reactor: FakeFlockerClient([node1, node2]), {node1.public_address, node2.public_address}, default_volume_size=DEFAULT_VOLUME_SIZE ) sample_size = 5 s = read_request_load_scenario(c, cluster, sample_size=sample_size) # Start and stop s.start() c.pump(repeat(1, sample_size)) s.stop() # Start again and verify the scenario succeeds d = s.start() c.pump(repeat(1, sample_size)) s.maintained().addBoth(lambda x: self.fail()) d.addCallback(lambda ignored: s.stop()) c.pump(repeat(1, sample_size)) self.successResultOf(d)
Example #26
Source File: test_read_request_load.py From flocker with Apache License 2.0 | 5 votes |
def test_read_request_load_succeeds(self, _logger): """ ``read_request_load_scenario`` starts and stops without collapsing. """ c = Clock() node1 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.1')) node2 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.2')) cluster = BenchmarkCluster( node1.public_address, lambda reactor: FakeFlockerClient([node1, node2]), {node1.public_address, node2.public_address}, default_volume_size=DEFAULT_VOLUME_SIZE ) sample_size = 5 s = read_request_load_scenario(c, cluster, sample_size=sample_size) d = s.start() # Request rate samples are recorded every second and we need to # collect enough samples to establish the rate which is defined # by `sample_size`. Therefore, advance the clock by # `sample_size` seconds to obtain enough samples. c.pump(repeat(1, sample_size)) s.maintained().addBoth(lambda x: self.fail()) d.addCallback(lambda ignored: s.stop()) def verify_scenario_returns_metrics(result): self.assertIsInstance(result, dict) d.addCallback(verify_scenario_returns_metrics) c.pump(repeat(1, sample_size)) self.successResultOf(d)
Example #27
Source File: test_read_request_load.py From flocker with Apache License 2.0 | 5 votes |
def make_cluster(self, make_flocker_client): """ Create a cluster that can be used by the scenario tests. """ node1 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.1')) node2 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.2')) return BenchmarkCluster( node1.public_address, lambda reactor: make_flocker_client( FakeFlockerClient([node1, node2]), reactor ), {node1.public_address, node2.public_address}, default_volume_size=DEFAULT_VOLUME_SIZE, )
Example #28
Source File: test_cputime.py From flocker with Apache License 2.0 | 5 votes |
def test_cpu_time(self): """ Fake Flocker cluster gives expected results. """ clock = Clock() node1 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.1')) node2 = Node(uuid=uuid4(), public_address=IPAddress('10.0.0.2')) metric = CPUTime( clock, BenchmarkCluster( IPAddress('10.0.0.1'), lambda reactor: FakeFlockerClient([node1, node2]), {}, None, ), _LocalRunner(), processes=[_pid_1_name] ) d = metric.measure(lambda: clock.advance(5)) # Although it is unlikely, it's possible that we could get a CPU # time != 0, so filter values out. def remove_process_times(node_cpu_times): for process_times in node_cpu_times.values(): if process_times: for process in process_times: if process != WALLCLOCK_LABEL: process_times[process] = 0 return node_cpu_times d.addCallback(remove_process_times) def check(result): self.assertEqual( result, { '10.0.0.1': {_pid_1_name: 0, WALLCLOCK_LABEL: 5}, '10.0.0.2': {_pid_1_name: 0, WALLCLOCK_LABEL: 5} } ) d.addCallback(check) return d
Example #29
Source File: test_cputime.py From flocker with Apache License 2.0 | 5 votes |
def test_get_node_init_process_name(self): """ Success results in output of string containing name of process 1. """ d = get_node_init_process_name( _LocalRunner(), Node(uuid=uuid4(), public_address=IPAddress('10.0.0.1')), ) def check(result): self.assertEqual(result, _pid_1_name) d.addCallback(check) return d
Example #30
Source File: cluster.py From flocker with Apache License 2.0 | 5 votes |
def public_address(self, hostname): """ Convert a node's internal hostname to a public address. If the hostname does not exist in ``_public_addresses``, just return the hostname, and hope it is public. :param IPAddress hostname: Hostname for Flocker node. :return IPAddress: Public IP address for node. """ return self._public_addresses.get(hostname, hostname)