本文整理汇总了Python中ipaddress.AddressValueError方法的典型用法代码示例。如果您正苦于以下问题:Python ipaddress.AddressValueError方法的具体用法?Python ipaddress.AddressValueError怎么用?Python ipaddress.AddressValueError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ipaddress
的用法示例。
在下文中一共展示了ipaddress.AddressValueError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scan_network
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def scan_network(self):
"""
Scan all the hosts specified in the internal hosts list :attr:`self.hosts`.
:return: A list of :class:`aztarna.sros.helpers.SROSHost` containing all the found hosts.
"""
try:
results = []
for port in self.ports:
for host_address in self.host_list:
results.append(self.scan_host(host_address, port))
for result in await asyncio.gather(*results):
if result:
self.hosts.append(result)
except AddressValueError:
print('Invalid network entered')
except Exception as e:
print(e)
示例2: ip_address_increment
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [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
示例3: ip_address_decrement
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [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
示例4: is_ipv4
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def is_ipv4(string):
"""
Checks if a string is a valid ip-address (v4)
:param string: String to check
:type string: str
:return: True if an ip, false otherwise.
:rtype: bool
"""
try:
ipaddress.IPv4Address(string)
return True
except ipaddress.AddressValueError:
return False
示例5: is_ipv6
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def is_ipv6(string):
"""
Checks if a string is a valid ip-address (v6)
:param string: String to check
:type string: str
:return: True if an ipv6, false otherwise.
:rtype: bool
"""
try:
ipaddress.IPv6Address(string)
return True
except ipaddress.AddressValueError:
return False
示例6: _get_ips
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _get_ips(self, msg, max_ips=0):
msg = msg + " Press enter after each one. When finished, just press enter."
ips = []
while 1:
ip_string = message_and_await_string(msg)
if not ip_string:
break
try:
ips.append(ipaddress.ip_address(ip_string))
if max_ips != 0 and len(ips) == max_ips:
break
except (ipaddress.AddressValueError, ValueError) as ex:
L.warning("{}: invalid IP address. Please re-enter.".format(ex))
if not ips:
L.warning('User did not provide any valid IP addresses')
return ips
示例7: get_external_ip
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def get_external_ip(self, ip_getter: str) -> Iterator[Deferred]:
log.info(
'Retrieving external IP from {!r} to generate server identifier.'.format(ip_getter))
try:
async with aiohttp.ClientSession() as session:
async with session.get(ip_getter) as response:
ip = await response.text()
ip = IPv4Address(ip.strip())
except AddressValueError as e:
log.warn('External IP getter service returned invalid data.\n'
'Please check the "ip_getter" setting in your config.')
return
except Exception as e: # pylint: disable=broad-except
log.warn("Getting external IP failed: {reason}", reason=e)
return
self.ip = ip
self.identifier = make_server_identifier(ip, self.port)
log.info('Server public ip address: {}:{}'.format(ip, self.port))
log.info('Public aos identifier: {}'.format(self.identifier))
示例8: add_peer_address
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def add_peer_address(self, peer_address):
if peer_address in self.peer_addresses:
return True
try:
ipaddress.IPv4Address(peer_address[0]).packed
except ipaddress.AddressValueError:
# peer_address[0] is probably an IPv6 address
if self.spv.logging_level <= INFO:
print("[NETWORK] peer address {} is not valid IPv4".format(peer_address[0]))
return False
if self.spv.logging_level <= DEBUG:
print("[NETWORK] new peer found", peer_address)
self.peer_addresses[peer_address] = {
'last_successful_connection_time': 0.0,
'index': self.peer_index,
}
self.update_peer_address(peer_address)
self.peer_index += 1
return True
示例9: ip_address
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def ip_address(self,
container: Container,
raise_error: bool = False
) -> Optional[Union[IPv4Address, IPv6Address]]:
"""
The IP address used by a given container, or None if no IP address has
been assigned to that container.
"""
# TODO: refactor!
api_client = docker.APIClient(base_url='unix://var/run/docker.sock')
docker_info = api_client.inspect_container(container.id)
address = docker_info['NetworkSettings']['IPAddress']
try:
return IPv4Address(address)
except ipaddress.AddressValueError:
try:
return IPv6Address(address)
except ipaddress.AddressValueError:
if raise_error:
raise
return None
示例10: parse_pp1_header
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def parse_pp1_header(data):
"""Return (src_tuple, dest_tuple, remaining_data)"""
if len(data) < len(PP1_MAGIC):
raise PPNoEnoughData()
if not data.startswith(PP1_MAGIC):
raise PPException('Not a PROXY PROTOCOL version 1 header.')
if b'\r\n' not in data:
if len(data) > 128:
raise PPException('Not a valid PROXY PROTOCOL header.')
raise PPNoEnoughData()
header, remaining_data = data.split(b'\r\n', 1)
try:
_, family, src, dest, sport, dport = header.split()
src = str(ip_address(src.decode()))
dest = str(ip_address(dest.decode()))
sport = int(sport)
dport = int(dport)
except ValueError:
raise PPException('Not a valid/supported PROXY PROTOCOL header.')
except AddressValueError:
raise PPException('Illegal IP address on PROXY PROTOCOL.')
return ((src, sport), (dest, dport), remaining_data)
示例11: qurl_from_user_input
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def qurl_from_user_input(urlstr: str) -> QUrl:
"""Get a QUrl based on a user input. Additionally handles IPv6 addresses.
QUrl.fromUserInput handles something like '::1' as a file URL instead of an
IPv6, so we first try to handle it as a valid IPv6, and if that fails we
use QUrl.fromUserInput.
WORKAROUND - https://bugreports.qt.io/browse/QTBUG-41089
FIXME - Maybe https://codereview.qt-project.org/#/c/93851/ has a better way
to solve this?
https://github.com/qutebrowser/qutebrowser/issues/109
Args:
urlstr: The URL as string.
Return:
The converted QUrl.
"""
# First we try very liberally to separate something like an IPv6 from the
# rest (e.g. path info or parameters)
match = re.fullmatch(r'\[?([0-9a-fA-F:.]+)\]?(.*)', urlstr.strip())
if match:
ipstr, rest = match.groups()
else:
ipstr = urlstr.strip()
rest = ''
# Then we try to parse it as an IPv6, and if we fail use
# QUrl.fromUserInput.
try:
ipaddress.IPv6Address(ipstr)
except ipaddress.AddressValueError:
return QUrl.fromUserInput(urlstr)
else:
return QUrl('http://[{}]{}'.format(ipstr, rest))
示例12: _is_ip_network
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _is_ip_network(value):
try:
ipaddress.IPv4Network(value)
return True
except (ValueError, ipaddress.AddressValueError):
pass
return False
示例13: _need_enable_ipv6
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _need_enable_ipv6(self, socket_type):
# Parse the URL
parsed_url = urlparse(self._address)
# Get the hostname portion
hostname = parsed_url.hostname
# See if the hostname is actually an interface name.
# In this case, return False.
if hostname in netifaces.interfaces():
return False
# Next, try to directly parse the hostname to determine if we have a
# literal IPv6 address.
try:
IPv6Address(hostname)
return True
except AddressValueError:
pass
# Finally, if we are setting up a zmq.DEALER docker (client), see if
# the hostname resolves to an IPv6 address.
if socket_type == zmq.DEALER:
try:
socket.getaddrinfo(parsed_url.hostname, 0,
socket.AddressFamily.AF_INET6,
socket.SocketKind.SOCK_STREAM)
return True
except socket.gaierror:
pass
# If none of the previous cases returns true, return false.
return False
示例14: _neighboring_network
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def _neighboring_network(cls, interface, after=True):
prefix = interface.network.prefixlen
network = interface.network
try:
neighbor = network.broadcast_address + 1 if after else network.network_address - 1
except ipaddress.AddressValueError:
return None
return ipaddress.ip_interface('{}/{}'.format(neighbor, prefix))
示例15: range_expander
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import AddressValueError [as 别名]
def range_expander(ip):
try:
network = ipaddress.IPv4Network(ip)
except ipaddress.AddressValueError:
fatal("Invalid IPv4 CIDR: {!r}".format(ip))
result = list(network)
return result