本文整理汇总了Python中ipaddress.IPv4Address方法的典型用法代码示例。如果您正苦于以下问题:Python ipaddress.IPv4Address方法的具体用法?Python ipaddress.IPv4Address怎么用?Python ipaddress.IPv4Address使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ipaddress
的用法示例。
在下文中一共展示了ipaddress.IPv4Address方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_next_hop_ordering
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def test_next_hop_ordering():
nhop1 = next_hop.NextHop(None, None)
nhop2 = next_hop.NextHop("if1", None)
nhop3 = next_hop.NextHop("if1", ipaddress.IPv4Address("1.1.1.1"))
nhop4 = next_hop.NextHop("if1", ipaddress.IPv4Address("2.2.2.2"))
nhop5 = next_hop.NextHop("if2", ipaddress.IPv4Address("1.1.1.1"))
nhop6 = next_hop.NextHop("if2", ipaddress.IPv6Address("1111:1111::"))
assert nhop1 < nhop2
assert nhop2 < nhop3
assert nhop3 < nhop4
assert nhop4 < nhop5
assert nhop5 < nhop6
# pylint:disable=unneeded-not
assert not nhop2 < nhop1
assert not nhop3 < nhop2
assert not nhop4 < nhop3
assert not nhop5 < nhop4
assert not nhop6 < nhop5
示例2: __lt__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def __lt__(self, other):
# String is not comparable with None
if (self.interface is None) and (other.interface is not None):
return True
if (self.interface is not None) and (other.interface is None):
return False
if self.interface < other.interface:
return True
if self.interface > other.interface:
return False
# Address is not comparable with None
if (self.address is None) and (other.address is not None):
return True
if (self.address is not None) and (other.address is None):
return False
# Address of different address families are not comparable
if (isinstance(self.address, ipaddress.IPv4Address) and
isinstance(other.address, ipaddress.IPv6Address)):
return True
if (isinstance(self.address, ipaddress.IPv6Address) and
isinstance(other.address, ipaddress.IPv4Address)):
return False
return self.address < other.address
示例3: bind_unused_port
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def bind_unused_port(sock: socket.socket, host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = 'localhost') -> int:
"""Bind the socket to a free port and return the port number.
This code is based on the code in the stdlib's test.test_support module."""
if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
with contextlib.suppress(socket.error):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
if not isinstance(host, str):
host = str(host)
if sock.family == socket.AF_INET:
if host == 'localhost':
sock.bind(('127.0.0.1', 0))
else:
sock.bind((host, 0))
elif sock.family == socket.AF_INET6:
if host == 'localhost':
sock.bind(('::1', 0, 0, 0))
else:
sock.bind((host, 0, 0, 0))
else:
raise CommunicationError("unsupported socket family: " + str(sock.family))
return sock.getsockname()[1]
示例4: is_blacklisted
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def is_blacklisted(self, value):
if is_ipv4(value):
for cidr in self.blacklisted_cidr:
try:
if IPv4Address(value) in cidr:
logging.debug("{} matches blacklisted cidr {}".format(value, cidr))
return True
except Exception as e:
logging.error("failed to compare {} to {}: {}".format(value, cidr, e))
report_exception()
return False
for dst in self.blacklisted_fqdn:
if is_subdomain(value, dst):
logging.debug("{} matches blacklisted fqdn {}".format(value, dst))
return True
return False
示例5: test_ip
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def test_ip(self):
"""
Returns IP patterns.
"""
rv = extract_ids(CERT_EVERYTHING)
assert [
DNSPattern(pattern=b"service.identity.invalid"),
DNSPattern(pattern=b"*.wildcard.service.identity.invalid"),
DNSPattern(pattern=b"service.identity.invalid"),
DNSPattern(pattern=b"single.service.identity.invalid"),
IPAddressPattern(pattern=ipaddress.IPv4Address(u"1.1.1.1")),
IPAddressPattern(pattern=ipaddress.IPv6Address(u"::1")),
IPAddressPattern(pattern=ipaddress.IPv4Address(u"2.2.2.2")),
IPAddressPattern(pattern=ipaddress.IPv6Address(u"2a00:1c38::53")),
] == rv
示例6: get_interface_netmask
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def get_interface_netmask(ip_address):
""" Get netmask of ip address' class
Args:
ip_address ('str'): ipv4 address
Returns:
ip address mask
Raises:
None
"""
class_a = IPv4Address("127.0.0.0")
class_b = IPv4Address("191.255.0.0")
class_c = IPv4Address("223.255.255.0")
ip_addr = IPv4Address(ip_address)
ip_class = [("/8", class_a), ("/16", class_b), ("/24", class_c)]
for e in ip_class:
if ip_addr < e[1]:
return e[0]
示例7: unconfigure_route_ref
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def unconfigure_route_ref(self, conf_obj, path, **kwargs):
paths = self._path_population([path], kwargs['device'])
# find position that neighbor (ip) sit
# replace ip string to IPv4Address object
for path in paths:
ipv4_index_list = [path.index(val) for val in path if '.' in str(val)]
ipv6_index_list = [path.index(val) for val in path if ':' in str(val)]
for index in ipv4_index_list:
path[index] = IPv4Address(path[index])
for index in ipv6_index_list:
path[index] = IPv6Address(path[index])
config = '\n'.join([str(conf_path) for conf_path in paths])
log.info('With following configuration:\n{c}'
.format(c=config))
Configure.conf_configure(device=kwargs['device'],
conf=conf_obj,
conf_structure=paths,
unconfig=True)
示例8: __new__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def __new__(cls, *args, **kwargs):
factory_cls = cls
if cls is PseudowireIPNeighbor:
try:
ip = kwargs['ip']
except KeyError:
raise TypeError('\'ip\' argument missing')
ip = ipaddress.ip_address(ip)
if isinstance(ip, ipaddress.IPv4Address):
factory_cls = PseudowireIPv4Neighbor
elif isinstance(ip, ipaddress.IPv6Address):
factory_cls = PseudowireIPv6Neighbor
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
示例9: __init__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def __init__(self, value):
if not isinstance(
value,
(
ipaddress.IPv4Address,
ipaddress.IPv6Address,
ipaddress.IPv4Network,
ipaddress.IPv6Network
)
):
raise TypeError(
"value must be an instance of ipaddress.IPv4Address, "
"ipaddress.IPv6Address, ipaddress.IPv4Network, or "
"ipaddress.IPv6Network"
)
self._value = value
示例10: _start
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def _start(self):
self._state = self._first_response
if isinstance(self._dst_host, ipaddress.IPv4Address):
# SOCKS4
dst_ip_packed = self._dst_host.packed
host_bytes = b''
else:
# SOCKS4a
dst_ip_packed = b'\0\0\0\1'
host_bytes = self._dst_host.encode() + b'\0'
if isinstance(self._auth, SOCKSUserAuth):
user_id = self._auth.username.encode()
else:
user_id = b''
# Send TCP/IP stream CONNECT request
return b''.join([b'\4\1', struct.pack('>H', self._dst_port),
dst_ip_packed, user_id, b'\0', host_bytes])
示例11: _detect_proxy
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def _detect_proxy(self):
"""Return True if it appears we can connect to a SOCKS proxy,
otherwise False.
"""
if self.protocol is SOCKS4a:
host, port = 'www.apple.com', 80
else:
host, port = ipaddress.IPv4Address('8.8.8.8'), 53
sock = await self._connect_one(host, port)
if isinstance(sock, socket.socket):
sock.close()
return True
# SOCKSFailure indicates something failed, but that we are
# likely talking to a proxy
return isinstance(sock, SOCKSFailure)
示例12: test_traverse_expander_no_cross_upper_boundary
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def test_traverse_expander_no_cross_upper_boundary(self):
ip = ipaddress.IPv4Address('192.168.1.254')
expand = 2
result = fierce.traverse_expander(ip, expand)
expected = [
ipaddress.IPv4Address('192.168.1.252'),
ipaddress.IPv4Address('192.168.1.253'),
ipaddress.IPv4Address('192.168.1.254'),
ipaddress.IPv4Address('192.168.1.255'),
]
assert expected == result
# Upper and lower bound tests are to avoid reintroducing out of
# bounds error from IPv4Address. (no_cross_*_boundary tests won't
# necessarily cover this; GitHub issue #29)
示例13: test_find_nearby_basic
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def test_find_nearby_basic(self):
resolver = 'unused'
ips = [
ipaddress.IPv4Address('192.168.1.0'),
ipaddress.IPv4Address('192.168.1.1'),
]
side_effect = [
[MockAnswer('sd1.example.com.')],
[MockAnswer('sd2.example.com.')],
]
with unittest.mock.patch.object(fierce, 'reverse_query', side_effect=side_effect):
result = fierce.find_nearby(resolver, ips)
expected = {
'192.168.1.0': 'sd1.example.com.',
'192.168.1.1': 'sd2.example.com.',
}
assert expected == result
示例14: ip_address_increment
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def ip_address_increment(self,
ip_address: str = '192.168.1.1',
exit_on_failure: bool = False,
exit_code: int = 33,
quiet: bool = False) -> Union[None, str]:
"""
Increment IPv4 address
:param ip_address: IPv4 address string (example: '192.168.1.1')
:param exit_on_failure: Exit in case of error (default: False)
:param exit_code: Set exit code integer (default: 33)
:param quiet: Quiet mode, if True no console output (default: False)
:return: IPv4 address string (example: '192.168.1.2')
"""
try:
return str(IPv4Address(ip_address) + 1)
except AddressValueError:
if quiet:
self.print_error('Bad IPv4 address: ', str(ip_address))
if exit_on_failure:
exit(exit_code)
return None
示例15: ip_address_decrement
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Address [as 别名]
def ip_address_decrement(self,
ip_address: str = '192.168.1.2',
exit_on_failure: bool = False,
exit_code: int = 34,
quiet: bool = False) -> Union[None, str]:
"""
Decrement IPv4 address
:param ip_address: IPv4 address string (example: '192.168.1.2')
:param exit_on_failure: Exit in case of error (default: False)
:param exit_code: Set exit code integer (default: 33)
:param quiet: Quiet mode, if True no console output (default: False)
:return: IPv4 address string (example: '192.168.1.1')
"""
try:
return str(IPv4Address(ip_address) - 1)
except AddressValueError:
if quiet:
self.print_error('Bad IPv4 address: ', str(ip_address))
if exit_on_failure:
exit(exit_code)
return None