本文整理汇总了Python中netaddr.valid_ipv4方法的典型用法代码示例。如果您正苦于以下问题:Python netaddr.valid_ipv4方法的具体用法?Python netaddr.valid_ipv4怎么用?Python netaddr.valid_ipv4使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netaddr
的用法示例。
在下文中一共展示了netaddr.valid_ipv4方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_ipv6_addr_by_EUI64
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def get_ipv6_addr_by_EUI64(cidr, mac):
"""Generate a IPv6 addr by EUI-64 with CIDR and MAC
:param str cidr: a IPv6 CIDR
:param str mac: a MAC address
:return: an IPv6 Address
:rtype: netaddr.IPAddress
"""
# Check if the prefix is IPv4 address
is_ipv4 = netaddr.valid_ipv4(cidr)
if is_ipv4:
msg = "Unable to generate IP address by EUI64 for IPv4 prefix"
raise TypeError(msg)
try:
eui64 = int(netaddr.EUI(mac).eui64())
prefix = netaddr.IPNetwork(cidr)
return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
except (ValueError, netaddr.AddrFormatError):
raise TypeError('Bad prefix or mac format for generating IPv6 '
'address by EUI-64: %(prefix)s, %(mac)s:'
% {'prefix': cidr, 'mac': mac})
except TypeError:
raise TypeError('Bad prefix type for generate IPv6 address by '
'EUI-64: %s' % cidr)
示例2: __init__
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def __init__(self, ip):
if not valid_ipv4(ip):
print('Error: the IPv4 address {} is invalid'.format(ip))
return
rec = requests.get('http://whois.arin.net/rest/ip/{}.txt'.format(ip))
if rec.status_code != 200:
print('Error')
return
ans = {}
r = re.compile(r"\s\s+")
b = rec.text.split('\n')
for l in b:
if l and l[0] != '#':
l = r.sub('', l)
a = l.split(':')
# print a
ans[a[0]] = a[1]
self.record = ans # remove?
self.CIDR = ans['CIDR']
self.NetName = ans['NetName']
self.NetRange = ans['NetRange']
self.Organization = ans['Organization']
self.Updated = ans['Updated']
# return None
示例3: validate_ipv4
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def validate_ipv4(address, parameter_name):
"""Verify that address represents a valid IPv4 address."""
try:
if netaddr.valid_ipv4(address):
return True
except Exception:
pass
raise exception.InvalidParameterValue(
value=address, parameter=parameter_name,
reason=_('Not a valid IP address'))
示例4: _get_vpn_gateways_external_ips
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def _get_vpn_gateways_external_ips(context, neutron):
vpcs = {vpc['id']: vpc
for vpc in db_api.get_items(context, 'vpc')}
external_ips = {}
routers = neutron.list_routers(
tenant_id=context.project_id)['routers']
for router in routers:
info = router['external_gateway_info']
if info:
for ip in info['external_fixed_ips']:
if netaddr.valid_ipv4(ip['ip_address']):
external_ips[router['id']] = ip['ip_address']
return {vgw['id']: external_ips.get(vpcs[vgw['vpc_id']]['os_id'])
for vgw in db_api.get_items(context, 'vgw')
if vgw['vpc_id']}
示例5: validate_ip_addr
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def validate_ip_addr(ip_addr):
if netaddr.valid_ipv4(ip_addr):
return lib_consts.IP_VERSION_4
elif netaddr.valid_ipv6(ip_addr):
return lib_consts.IP_VERSION_6
else:
raise bgp_driver_exc.InvalidParamType(param=ip_addr,
param_type='ip-address')
示例6: add_to_global_table
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def add_to_global_table(self, prefix, nexthop=None,
is_withdraw=False):
src_ver_num = 1
peer = None
# set mandatory path attributes
origin = BGPPathAttributeOrigin(BGP_ATTR_ORIGIN_IGP)
aspath = BGPPathAttributeAsPath([[]])
pathattrs = OrderedDict()
pathattrs[BGP_ATTR_TYPE_ORIGIN] = origin
pathattrs[BGP_ATTR_TYPE_AS_PATH] = aspath
net = netaddr.IPNetwork(prefix)
ip = str(net.ip)
masklen = net.prefixlen
if netaddr.valid_ipv4(ip):
_nlri = IPAddrPrefix(masklen, ip)
if nexthop is None:
nexthop = '0.0.0.0'
p = Ipv4Path
else:
_nlri = IP6AddrPrefix(masklen, ip)
if nexthop is None:
nexthop = '::'
p = Ipv6Path
new_path = p(peer, _nlri, src_ver_num,
pattrs=pathattrs, nexthop=nexthop,
is_withdraw=is_withdraw)
# add to global ipv4 table and propagates to neighbors
self.learn_path(new_path)
示例7: _connect_tcp
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def _connect_tcp(self, peer_addr, conn_handler, time_out=None,
bind_address=None, password=None):
"""Creates a TCP connection to given peer address.
Tries to create a socket for `timeout` number of seconds. If
successful, uses the socket instance to start `client_factory`.
The socket is bound to `bind_address` if specified.
"""
LOG.debug('Connect TCP called for %s:%s', peer_addr[0], peer_addr[1])
if netaddr.valid_ipv4(peer_addr[0]):
family = socket.AF_INET
else:
family = socket.AF_INET6
with Timeout(time_out, socket.error):
sock = socket.socket(family)
if bind_address:
sock.bind(bind_address)
if password:
sockopt.set_tcp_md5sig(sock, peer_addr[0], password)
sock.connect(peer_addr)
# socket.error exception is rasied in cese of timeout and
# the following code is executed only when the connection
# is established.
# Connection name for pro-active connection is made up of
# local end address + remote end address
local = self.get_localname(sock)[0]
remote = self.get_remotename(sock)[0]
conn_name = ('L: ' + local + ', R: ' + remote)
self._asso_socket_map[conn_name] = sock
# If connection is established, we call connection handler
# in a new thread.
self._spawn(conn_name, conn_handler, sock)
return sock
#
# Sink
#
示例8: _set_password
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def _set_password(self, address, password):
if netaddr.valid_ipv4(address):
family = socket.AF_INET
else:
family = socket.AF_INET6
for sock in self.listen_sockets.values():
if sock.family == family:
sockopt.set_tcp_md5sig(sock, address, password)
示例9: valid_ip_address
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def valid_ip_address(addr):
if not netaddr.valid_ipv4(addr) and not netaddr.valid_ipv6(addr):
return False
return True
示例10: prefix_add
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def prefix_add(self, prefix, next_hop=None, route_dist=None):
""" This method adds a new prefix to be advertized.
``prefix`` must be the string representation of an IP network
(e.g., 10.1.1.0/24).
``next_hop`` specifies the next hop address for this
prefix. This parameter is necessary for only VPNv4 and VPNv6
address families.
``route_dist`` specifies a route distinguisher value. This
parameter is necessary for only VPNv4 and VPNv6 address
families.
"""
func_name = 'network.add'
networks = {}
networks[PREFIX] = prefix
if next_hop:
networks[NEXT_HOP] = next_hop
if route_dist:
func_name = 'prefix.add_local'
networks[ROUTE_DISTINGUISHER] = route_dist
rf, p = self._check_rf_and_normalize(prefix)
networks[ROUTE_FAMILY] = rf
networks[PREFIX] = p
if rf == vrfs.VRF_RF_IPV6 and netaddr.valid_ipv4(next_hop):
# convert the next_hop to IPv4-Mapped IPv6 Address
networks[NEXT_HOP] = \
str(netaddr.IPAddress(next_hop).ipv6())
return call(func_name, **networks)
示例11: _is_ip
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def _is_ip(self, domain):
'''
This extra parsing handles a variety of edge cases such as:
- http://192.168.1.1
- http://192.168.1.1:81
- 192.168.1.1:81
'''
if valid_ipv4(domain):
return True
if urlparse(domain).scheme != '':
domain = urlparse(domain).netloc
if ':' in domain:
domain = domain[:domain.rindex(':')]
return valid_ipv4(domain)
示例12: ip_route_get_to
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def ip_route_get_to(host):
"""Get interface IP that routes to hostname or IP address
Args:
host (str): Hostname or IP address
Returns:
str: Interface IP with route to host
"""
log = logger.getlogger()
# Check if host is given as IP address
if netaddr.valid_ipv4(host, flags=0):
host_ip = host
else:
if host == socket.gethostname():
host = 'localhost'
try:
host_ip = socket.gethostbyname(host)
except socket.gaierror as exc:
log.warning("Unable to resolve host to IP: '{}' exception: '{}'"
.format(host, exc))
with IPRoute() as ipr:
route = ipr.route('get', dst=host_ip)[0]['attrs'][3][1]
return route
示例13: _validate_host_list_network
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def _validate_host_list_network(host_list):
"""Validate all hosts in list are pingable
Args:
host_list (list): List of hostnames or IP addresses
Returns:
bool: True if all hosts are pingable
Raises:
UserException: If list item will not resolve or ping
"""
log = logger.getlogger()
for host in host_list:
# Check if host is given as IP address
if not netaddr.valid_ipv4(host, flags=0):
try:
socket.gethostbyname(host)
except socket.gaierror as exc:
log.debug("Unable to resolve host to IP: '{}' exception: '{}'"
.format(host, exc))
raise UserException("Unable to resolve hostname '{}'!"
.format(host))
else:
raise UserException('Client nodes must be defined using hostnames '
f'(IP address found: {host})!')
# Ping IP
try:
bash_cmd('fping -u {}'.format(' '.join(host_list)))
except CalledProcessError as exc:
msg = "Ping failed on hosts:\n{}".format(exc.output)
log.debug(msg)
raise UserException(msg)
log.debug("Software inventory host fping validation passed")
return True
示例14: is_valid_ip
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def is_valid_ip(ip):
"""Return True if the IP is either v4 or v6
Return False if invalid.
"""
return netaddr.valid_ipv4(ip) or netaddr.valid_ipv6(ip)
示例15: is_valid_ipv4
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import valid_ipv4 [as 别名]
def is_valid_ipv4(address):
"""Verify that address represents a valid IPv4 address."""
try:
return netaddr.valid_ipv4(address)
except Exception:
return False