本文整理汇总了Python中ipaddress.IPv4Interface方法的典型用法代码示例。如果您正苦于以下问题:Python ipaddress.IPv4Interface方法的具体用法?Python ipaddress.IPv4Interface怎么用?Python ipaddress.IPv4Interface使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ipaddress
的用法示例。
在下文中一共展示了ipaddress.IPv4Interface方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testIpFromInt
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
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)
示例2: testEqual
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
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)
示例3: __init__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def __init__(self, if1: IPIntf, if2: IPIntf,
if1address: Union[str, IPv4Interface, IPv6Interface],
if2address: Union[str, IPv4Interface, IPv6Interface],
bidirectional=True):
""":param if1: The first interface of the tunnel
:param if2: The second interface of the tunnel
:param if1address: The ip_interface address for if1
:param if2address: The ip_interface address for if2
:param bidirectional: Whether both end of the tunnel should be
established or not. GRE is stateless so there is
no handshake per-say, however if one end of the
tunnel is not established, the kernel will drop
by default the encapsulated packets."""
self.if1, self.if2 = if1, if2
self.ip1, self.gre1 = (ip_interface(str(if1address)),
self._gre_name(if1))
self.ip2, self.gre2 = (ip_interface(str(if2address)),
self._gre_name(if2))
self.bidirectional = bidirectional
self.setup_tunnel()
示例4: __init__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def __init__(self, name,
config: Union[Type[RouterConfig],
Tuple[Type[RouterConfig],
Dict]] = BasicRouterConfig,
password='zebra',
lo_addresses: Sequence[Union[str, IPv4Interface,
IPv6Interface]] = (),
*args, **kwargs):
""":param password: The password for the routing daemons vtysh access
:param lo_addresses: The list of addresses to set on the loopback
interface"""
super().__init__(name, config=config, *args, **kwargs)
self.password = password
# This interface already exists in the node,
# so no need to move it
lo = IPIntf('lo', node=self, port=-1, moveIntfFn=lambda x, y: None)
lo.ip = lo_addresses
示例5: covering_cidr
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
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:
示例6: _str_conf
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def _str_conf(self, conf_v):
if isinstance(conf_v, (bool, str, int)):
return conf_v
if isinstance(conf_v, (
ipaddress.IPv4Address, ipaddress.IPv4Interface, ipaddress.IPv4Network,
ipaddress.IPv6Address, ipaddress.IPv6Interface, ipaddress.IPv6Network)):
return str(conf_v)
if isinstance(conf_v, (dict, OrderedDict)):
return {str(i): self._str_conf(j) for i, j in conf_v.items() if j is not None}
if isinstance(conf_v, (list, tuple, frozenset)):
return tuple([self._str_conf(i) for i in conf_v if i is not None])
if isinstance(conf_v, Conf):
for i in ('name', '_id'):
if hasattr(conf_v, i):
return getattr(conf_v, i)
return None
示例7: to_ip
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def to_ip(data, *args):
# for py2 support need to convert data to unicode:
if _ttp_["python_major_version"] is 2:
ipaddr_data = unicode(data)
elif _ttp_["python_major_version"] is 3:
ipaddr_data = data
if "ipv4" in args:
if "/" in ipaddr_data or " " in ipaddr_data:
return ipaddress.IPv4Interface(ipaddr_data.replace(" ", "/")), None
else:
return ipaddress.IPv4Address(ipaddr_data), None
elif "ipv6" in args:
if "/" in ipaddr_data:
return ipaddress.IPv6Interface(ipaddr_data), None
else:
return ipaddress.IPv6Address(ipaddr_data), None
elif "/" in ipaddr_data or " " in ipaddr_data:
return ipaddress.ip_interface(ipaddr_data.replace(" ", "/")), None
else:
return ipaddress.ip_address(ipaddr_data), None
示例8: _set_static_iface_ip
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def _set_static_iface_ip(ifname, ipv4_if, is_root):
"""Set static IP address for target network interface
Args:
ifname : Network device name
ipv4_if : IPv4Interface object with the target interface address
is_root : (bool) whether running as root
"""
isinstance(ipv4_if, IPv4Interface)
addr = str(ipv4_if.ip)
addr_with_prefix = ipv4_if.with_prefixlen
netmask = str(ipv4_if.netmask)
if (which("netplan") is not None):
_add_to_netplan(ifname, addr_with_prefix, is_root)
elif (os.path.exists("/etc/network/interfaces.d/")):
_add_to_interfaces_d(ifname, addr, netmask, is_root)
elif (os.path.exists("/etc/sysconfig/network-scripts")):
_add_to_sysconfig_net_scripts(ifname, addr, netmask, is_root)
else:
raise ValueError("Could not set a static IP address on interface "
"{}".format(ifname))
示例9: _set_ip
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def _set_ip(net_if, ip_addr, verbose):
"""Set the IP of the DVB network interface
Args:
net_if : DVB network interface name
ip_addr : Target IP address for the DVB interface slash subnet mask
verbose : Controls verbosity
"""
is_root = (os.geteuid() == 0)
inet_if = IPv4Interface(ip_addr)
# Flush previous IP
if (not is_root):
print("Flush any IP address from {}:\n".format(net_if))
res = util.run_or_print_root_cmd(["ip", "address", "flush", "dev", net_if],
logger)
# Configure new static IP
_set_static_iface_ip(net_if, inet_if, is_root)
示例10: get_interface
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def get_interface(ip_address: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]) \
-> Union[ipaddress.IPv4Interface, ipaddress.IPv6Interface]:
"""tries to find the network interface that connects to the given host's address"""
if isinstance(ip_address, str):
ip_address = get_ip_address(ip_address)
family = socket.AF_INET if ip_address.version == 4 else socket.AF_INET6
with socket.socket(family, socket.SOCK_DGRAM) as sock:
sock.connect((str(ip_address), 53)) # 53=dns
return ipaddress.ip_interface(sock.getsockname()[0])
示例11: register_ipaddress
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
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)
示例12: __new__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def __new__(cls, *args, **kwargs):
factory_cls = cls
if cls is IPNeighbor:
if not kwargs and len(args) == 1 \
and isinstance(args[0], IPNeighbor):
# Copy constructor
factory_cls = type(args[0])
else:
if not kwargs and len(args) == 1:
ip = args[0]
else:
try:
ip = kwargs['ip']
except KeyError:
raise TypeError('\'ip\' argument missing')
if isinstance(ip, (ipaddress.IPv4Interface,
ipaddress.IPv6Interface)):
ip = ip.ip
elif isinstance(ip, (ipaddress.IPv4Address,
ipaddress.IPv6Address)):
pass
else:
ip = ipaddress.ip_address(ip)
if isinstance(ip, ipaddress.IPv4Address):
factory_cls = IPv4Neighbor
elif isinstance(ip, ipaddress.IPv6Address):
factory_cls = IPv6Neighbor
else:
raise ValueError(ip)
if factory_cls is not cls:
self = factory_cls.__new__(factory_cls, *args, **kwargs)
elif super().__new__ is object.__new__:
self = super().__new__(factory_cls)
else:
self = super().__new__(factory_cls, *args, **kwargs)
return self
示例13: __init__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def __init__(self, ip, **kwargs):
if isinstance(ip, (ipaddress.IPv4Interface, ipaddress.IPv6Interface)):
ip = ip.ip
elif isinstance(ip, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
pass
else:
ip = ipaddress.ip_address(ip)
self._ip = ip
super().__init__(**kwargs)
示例14: _load_interfaces
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
def _load_interfaces(self):
fw_settings = load_configuration('config')['settings']
server_settings = load_configuration('dhcp_server')['dhcp_server']
fw_intf = fw_settings['interfaces']
dhcp_intfs = server_settings['interfaces']
# ident
for intf in self.DHCPServer._intfs:
# friendly name
for _intf, settings in dhcp_intfs.items():
# ensuring the iterfaces match since we cannot guarantee order
if (intf != settings['ident']): continue
# passing over disabled server interfaces. NOTE: DEF temporary
if not dhcp_intfs[_intf]['enabled']: continue
# creating ipv4 interface object which will be associated with the ident in the config.
# this can then be used by the server to identify itself as well as generate its effective
# subnet based on netmask for ip handouts or membership tests.
intf_ip = IPv4Interface(str(fw_intf[_intf]['ip']) + '/' + str(fw_intf[_intf]['netmask']))
# initializing server options so the auto loader doesnt have to worry about it.
self.DHCPServer.options[intf] = {}
# updating general network information for interfaces on server class object. these will never change
# while the server is running. for interfaces changes, the server must be restarted.
self.DHCPServer.intf_settings[intf] = {'ip': intf_ip}
# custom dictionary to manage dhcp server leases including timeouts, updates, or persistence (store to disk)
示例15: setUp
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Interface [as 别名]
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')