我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ipaddress.IPv4Interface()。
def test_inet_cast(self): import ipaddress as ip cur = self.conn.cursor() psycopg2.extras.register_ipaddress(cur) cur.execute("select null::inet") self.assertTrue(cur.fetchone()[0] is None) cur.execute("select '127.0.0.1/24'::inet") obj = cur.fetchone()[0] self.assertTrue(isinstance(obj, ip.IPv4Interface), repr(obj)) self.assertEqual(obj, ip.ip_interface('127.0.0.1/24')) cur.execute("select '::ffff:102:300/128'::inet") obj = cur.fetchone()[0] self.assertTrue(isinstance(obj, ip.IPv6Interface), repr(obj)) self.assertEqual(obj, ip.ip_interface('::ffff:102:300/128'))
def test_inet_cast(self): import ipaddress as ip cur = self.conn.cursor() psycopg2.extras.register_ipaddress(cur) cur.execute("select null::inet") self.assert_(cur.fetchone()[0] is None) cur.execute("select '127.0.0.1/24'::inet") obj = cur.fetchone()[0] self.assert_(isinstance(obj, ip.IPv4Interface), repr(obj)) self.assertEquals(obj, ip.ip_interface('127.0.0.1/24')) cur.execute("select '::ffff:102:300/128'::inet") obj = cur.fetchone()[0] self.assert_(isinstance(obj, ip.IPv6Interface), repr(obj)) self.assertEquals(obj, ip.ip_interface('::ffff:102:300/128'))
def network(cls, value, raise_exception=False): """ Network address validation """ if not isinstance(value, basestring): if raise_exception: raise TypeError('Invalid type \'{}\''.format(type(value))) return False terms = value.split() if len(terms) is 2: if cls.ip(terms[0]): if cls.netmask(terms[1]): terms[1] = NetTest.convert.netmask.prefix(terms[1]) elif cls.wildcard(terms[1]): terms[1] = NetTest.convert.wildcard.prefix(terms[1]) terms[1] = unicode(terms[1]) value = u'/'.join(terms) try: value = unicode(value) ipaddress.IPv4Interface(value) except (ValueError, TypeError): if raise_exception: raise return False return True
def covering_cidr(ips: List[str]) -> str: """ Given list of IPs, return CIDR that covers them all. Presumes it's at least a /24. """ def collapse(ns): return list(ipaddress.collapse_addresses(ns)) assert len(ips) > 0 networks = collapse([ ipaddress.IPv4Interface(ip + "/24").network for ip in ips ]) # Increase network size until it combines everything: while len(networks) > 1: networks = collapse([networks[0].supernet()] + networks[1:]) return networks[0].with_prefixlen # Script to dump resolved IPs to stdout as JSON list:
def testIpFromInt(self): self.assertEqual(self.ipv4_interface._ip, ipaddress.IPv4Interface(16909060)._ip) ipv4 = ipaddress.ip_network('1.2.3.4') ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1') self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address))) self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address))) v6_int = 42540616829182469433547762482097946625 self.assertEqual(self.ipv6_interface._ip, ipaddress.IPv6Interface(v6_int)._ip) self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version, 4) self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version, 6)
def testEqual(self): self.assertTrue(self.ipv4_interface == ipaddress.IPv4Interface('1.2.3.4/24')) self.assertFalse(self.ipv4_interface == ipaddress.IPv4Interface('1.2.3.4/23')) self.assertFalse(self.ipv4_interface == ipaddress.IPv6Interface('::1.2.3.4/24')) self.assertFalse(self.ipv4_interface == '') self.assertFalse(self.ipv4_interface == []) self.assertFalse(self.ipv4_interface == 2) self.assertTrue(self.ipv6_interface == ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64')) self.assertFalse(self.ipv6_interface == ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63')) self.assertFalse(self.ipv6_interface == ipaddress.IPv4Interface('1.2.3.4/23')) self.assertFalse(self.ipv6_interface == '') self.assertFalse(self.ipv6_interface == []) self.assertFalse(self.ipv6_interface == 2)
def check_if_ipv4address(potential_address): """ check if ipv4address this is used in conjunction with the flexible parse function and determines if the word is an ipaddress in a smart way """ try: ipaddress.IPv4Interface(potential_address) return True except ipaddress.AddressValueError: return False
def register_ipaddress(conn_or_curs=None): """ Register conversion support between `ipaddress` objects and `network types`__. :param conn_or_curs: the scope where to register the type casters. If `!None` register them globally. After the function is called, PostgreSQL :sql:`inet` values will be converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface` objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or `~ipaddress.IPv6Network`. .. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html """ global ipaddress import ipaddress global _casters if _casters is None: _casters = _make_casters() for c in _casters: register_type(c, conn_or_curs) for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface, ipaddress.IPv4Network, ipaddress.IPv6Network]: register_adapter(t, adapt_ipaddress)
def test_inet_array_cast(self): import ipaddress as ip cur = self.conn.cursor() psycopg2.extras.register_ipaddress(cur) cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::inet[]") l = cur.fetchone()[0] self.assertTrue(l[0] is None) self.assertEqual(l[1], ip.ip_interface('127.0.0.1')) self.assertEqual(l[2], ip.ip_interface('::ffff:102:300/128')) self.assertTrue(isinstance(l[1], ip.IPv4Interface), l) self.assertTrue(isinstance(l[2], ip.IPv6Interface), l)
def setup(self): self.netmasks = list() self.wildcards = list() for x in range(0, 33): netmask = IPv4Int(u'255.255.255.255/{0}'.format(x)).network.network_address.exploded self.netmasks.append(netmask) wildcard = IPv4Int(u'0.0.0.0/{0}'.format(x)).network.hostmask.exploded self.wildcards.append(wildcard)
def setup(self): self.wildcards = [ipaddress.IPv4Interface( unicode('0.0.0.0/{}'.format(x))).network.hostmask.exploded for x in range(0, 33)] self.netmasks = [ipaddress.IPv4Interface( unicode('255.255.255.255/{}'.format(x))) .network.network_address.exploded for x in range(0, 33)]
def _get_network_object(cls, network): cls.ip(network, raise_exception=True) or cls.ip(network, raise_exception=True) network = NetTest.convert.string.cidr(network) network = ipaddress.IPv4Interface(network).network return network
def cidr(cls, value): """ Convert a string to a network CIDR """ value = cls._standardize_cidr_format(value) value = ipaddress.IPv4Interface(value).network.exploded return value
def address_builder(value): if isinstance(value, (basestring)): try: value = IPv4Interface(unicode(value)).network except AddressValueError: message = 'Unsupported string initialization format \'{}\'' message = message.format(value) raise ValueError(message) elif not isinstance(value, IPv4Network): raise_type_exception(value, (IPv4Network, ), 'build with') return value
def monkey_patch_support_for_python2(): from future import standard_library standard_library.install_aliases() # Monkey patch the backported ipaddress module with alternative # versions that accept string addresses, in addition to unicode # addresses, in python2 code. # # This keep compatibility simple. Slightly complicated by the fact # that some of these classes inherit from each other. import ipaddress def python2_compat(cls, bases=()): def __init__(self, address, *args, **kwargs): if isinstance(address, str) and len(address) > 4: address = address.decode('utf-8') return cls.__init__(self, address, *args, **kwargs) return type(cls.__name__, (cls,) + bases, {'__init__': __init__}) ipaddress.IPv4Network = python2_compat(ipaddress.IPv4Network) ipaddress.IPv4Address = python2_compat(ipaddress.IPv4Address) ipaddress.IPv4Interface = python2_compat(ipaddress.IPv4Interface, bases=(ipaddress.IPv4Address,)) ipaddress.IPv6Network = python2_compat(ipaddress.IPv6Network) ipaddress.IPv6Address = python2_compat(ipaddress.IPv6Address) ipaddress.IPv6Interface = python2_compat(ipaddress.IPv6Interface, bases=(ipaddress.IPv6Address,))
def test_inet_array_cast(self): import ipaddress as ip cur = self.conn.cursor() psycopg2.extras.register_ipaddress(cur) cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::inet[]") l = cur.fetchone()[0] self.assert_(l[0] is None) self.assertEquals(l[1], ip.ip_interface('127.0.0.1')) self.assertEquals(l[2], ip.ip_interface('::ffff:102:300/128')) self.assert_(isinstance(l[1], ip.IPv4Interface), l) self.assert_(isinstance(l[2], ip.IPv6Interface), l)
def setUp(self): self.ipv4_address = ipaddress.IPv4Address('1.2.3.4') self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24') self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24') #self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255') self.ipv6_address = ipaddress.IPv6Interface( '2001:658:22a:cafe:200:0:0:1') self.ipv6_interface = ipaddress.IPv6Interface( '2001:658:22a:cafe:200:0:0:1/64') self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64')
def testRepr(self): self.assertEqual("IPv4Interface('1.2.3.4/32')", repr(ipaddress.IPv4Interface('1.2.3.4'))) self.assertEqual("IPv6Interface('::1/128')", repr(ipaddress.IPv6Interface('::1'))) # issue57
def testZeroNetmask(self): ipv4_zero_netmask = ipaddress.IPv4Interface('1.2.3.4/0') self.assertEqual(int(ipv4_zero_netmask.network.netmask), 0) self.assertTrue(ipv4_zero_netmask.network._is_valid_netmask( str(0))) self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0')) self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0.0.0.0')) self.assertFalse(ipv4_zero_netmask._is_valid_netmask('invalid')) ipv6_zero_netmask = ipaddress.IPv6Interface('::1/0') self.assertEqual(int(ipv6_zero_netmask.network.netmask), 0) self.assertTrue(ipv6_zero_netmask.network._is_valid_netmask( str(0)))
def testGetSupernet(self): self.assertEqual(self.ipv4_network.supernet().prefixlen, 23) self.assertEqual(str(self.ipv4_network.supernet().network_address), '1.2.2.0') self.assertEqual( ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(), ipaddress.IPv4Network('0.0.0.0/0')) self.assertEqual(self.ipv6_network.supernet().prefixlen, 63) self.assertEqual(str(self.ipv6_network.supernet().network_address), '2001:658:22a:cafe::') self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(), ipaddress.IPv6Network('::0/0'))
def testNotEqual(self): self.assertFalse(self.ipv4_interface != ipaddress.IPv4Interface('1.2.3.4/24')) self.assertTrue(self.ipv4_interface != ipaddress.IPv4Interface('1.2.3.4/23')) self.assertTrue(self.ipv4_interface != ipaddress.IPv6Interface('::1.2.3.4/24')) self.assertTrue(self.ipv4_interface != '') self.assertTrue(self.ipv4_interface != []) self.assertTrue(self.ipv4_interface != 2) self.assertTrue(self.ipv4_address != ipaddress.IPv4Address('1.2.3.5')) self.assertTrue(self.ipv4_address != '') self.assertTrue(self.ipv4_address != []) self.assertTrue(self.ipv4_address != 2) self.assertFalse(self.ipv6_interface != ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64')) self.assertTrue(self.ipv6_interface != ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63')) self.assertTrue(self.ipv6_interface != ipaddress.IPv4Interface('1.2.3.4/23')) self.assertTrue(self.ipv6_interface != '') self.assertTrue(self.ipv6_interface != []) self.assertTrue(self.ipv6_interface != 2) self.assertTrue(self.ipv6_address != ipaddress.IPv4Address('1.2.3.4')) self.assertTrue(self.ipv6_address != '') self.assertTrue(self.ipv6_address != []) self.assertTrue(self.ipv6_address != 2)
def testSlash32Constructor(self): self.assertEqual(str(ipaddress.IPv4Interface( '1.2.3.4/255.255.255.255')), '1.2.3.4/32')
def testSlash0Constructor(self): self.assertEqual(str(ipaddress.IPv4Interface('1.2.3.4/0.0.0.0')), '1.2.3.4/0')
def testEmbeddedIpv4(self): ipv4_string = '192.168.0.1' ipv4 = ipaddress.IPv4Interface(ipv4_string) v4compat_ipv6 = ipaddress.IPv6Interface('::%s' % ipv4_string) self.assertEqual(int(v4compat_ipv6.ip), int(ipv4.ip)) v4mapped_ipv6 = ipaddress.IPv6Interface('::ffff:%s' % ipv4_string) self.assertNotEqual(v4mapped_ipv6.ip, ipv4.ip) self.assertRaises(ipaddress.AddressValueError, ipaddress.IPv6Interface, '2001:1.1.1.1:1.1.1.1') # Issue 67: IPv6 with embedded IPv4 address not recognized.
def testIpStrFromPrefixlen(self): ipv4 = ipaddress.IPv4Interface('1.2.3.4/24') self.assertEqual(ipv4._ip_string_from_prefix(), '255.255.255.0') self.assertEqual(ipv4._ip_string_from_prefix(28), '255.255.255.240')
def run(): from fluxclient.upnp.misc import parse_network_config kw = {} ret = input("Wifi Mode (0=host,1=client)[1]: ").strip("\n") if ret == "0": kw["wifi_mode"] = "host" else: kw["wifi_mode"] = "client" kw["ssid"] = input("SSID: ").strip("\n") ret = input("Is SSID hidden? (y/n)[n]: ").strip("\n") if ret.upper() == "Y": kw["scan_ssid"] = "1" ret = input("Wifi-Protection (0=None,1=WEP,2=WPA2-PSK)[2]: ").strip("\n") if ret == "0": kw["security"] = "None" elif ret == "1": kw["security"] = "WEP" kw["wepkey"] = input("Wifi password: ").strip("\n") else: kw["security"] = "WPA2-PSK" kw["psk"] = input("Wifi password: ").strip("\n") ret = input("Use DHCP? (0=YES,1=NO)[0]: ").strip("\n") if ret == "1": kw["method"] = "static" ipaddr = IPv4Interface( input("IP Address (example: \"192.168.0.1/24\"): ").strip("\n")) kw["ipaddr"] = str(ipaddr.ip) kw["mask"] = int(ipaddr.with_prefixlen.split("/")[-1]) gw = IPv4Address(input("Gateway: ").strip("\n")) kw["route"] = str(gw) kw["ns"] = input("DNS: ").strip("\n") else: kw["method"] = "dhcp" return parse_network_config(**kw)
def testZeroNetmask(self): ipv4_zero_netmask = ipaddress.IPv4Interface('1.2.3.4/0') self.assertEqual(int(ipv4_zero_netmask.network.netmask), 0) self.assertEqual(ipv4_zero_netmask._prefix_from_prefix_string('0'), 0) self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0')) self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0.0.0.0')) self.assertFalse(ipv4_zero_netmask._is_valid_netmask('invalid')) ipv6_zero_netmask = ipaddress.IPv6Interface('::1/0') self.assertEqual(int(ipv6_zero_netmask.network.netmask), 0) self.assertEqual(ipv6_zero_netmask._prefix_from_prefix_string('0'), 0)
def get_client_ip(request): ip = get_real_ip(request) if ip: try: interface = ipaddress.IPv6Interface('%s/%i' % (ip, settings.IPV6_PRIVACY_MASK)) except ipaddress.AddressValueError: interface = ipaddress.IPv4Interface('%s/%i' % (ip, settings.IPV4_PRIVACY_MASK)) return str(interface.network.network_address) else: return None