本文整理汇总了Python中netaddr.valid_ipv4函数的典型用法代码示例。如果您正苦于以下问题:Python valid_ipv4函数的具体用法?Python valid_ipv4怎么用?Python valid_ipv4使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了valid_ipv4函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_from_tuple
def find_from_tuple(cls, link):
"""
Find link by providing a tuple with two ip addresses or two mac addresses
:param link: tuple with two string elements indicating source and destination (ip or mac addresses)
:returns: Link object
"""
try:
a = link[0]
b = link[1]
except IndexError:
raise ValueError('Expecting tuple with source and destination')
# find interfaces
if (valid_ipv4(a) and valid_ipv4(b)) or (valid_ipv6(a) and valid_ipv6(b)):
try:
a = Ip.objects.get(address=a).interface
b = Ip.objects.get(address=b).interface
except Ip.DoesNotExist as e:
raise LinkDataNotFound(e)
elif valid_mac(a) and valid_mac(b):
try:
a = Interface.objects.get(mac=a)
b = Interface.objects.get(mac=b)
except Interface.DoesNotExist as e:
raise LinkDataNotFound(e)
else:
raise ValueError('Expecting valid ipv4, ipv6 or mac address')
# find link with interfaces
# inverse order is also ok
q = Q(interface_a=a, interface_b=b) | Q(interface_a=b, interface_b=a)
link = Link.objects.filter(q).first()
if link is None:
raise LinkNotFound('Link matching query does not exist',
interface_a=a,
interface_b=b)
return link
示例2: main
def main(args):
'''
Obtain necessary input to execute ping sweep:
telnet-pingsweep [--version] [-v|--verbose] [-f|--file <file.yaml>]
<starting-address-range> <ending-address-range>
'''
parser = argparse.ArgumentParser(description='Connect to a specified router and run a '
'command')
parser.add_argument('--version', action='version', version=__version__)
parser.add_argument('-v', '--verbose', action='store_true', help='display verbose output',
default=False)
parser.add_argument('-f', '--file', help='specify YAML file to read router info from',
default=ROUTER_FILE)
parser.add_argument('-o', '--output', help='specify output file to write results to')
parser.add_argument('addr_start', help='starting address for sweep')
parser.add_argument('addr_end', help='ending address for sweep')
args = parser.parse_args()
# Pre-flight checks
myrouter_data = yaml_input(args.file, args.verbose)
# Validate IP addresses
if netaddr.valid_ipv4(args.addr_start):
addr_start = netaddr.IPAddress(args.addr_start)
else:
sys.exit('Invalid IPv4 address: {}'.format(args.start))
if netaddr.valid_ipv4(args.addr_end):
addr_end = netaddr.IPAddress(args.addr_end)
else:
sys.exit('Invalid IPv4 address: {}'.format(args.start))
if addr_end <= addr_start:
sys.exit('Ending address must be after starting address.')
if (addr_end - addr_start).value > 254:
sys.exit('Largest range of addresses which may be swept is limited to 254.')
addr_range = netaddr.IPRange(addr_start, addr_end)
myrouter = Netinfnode(myrouter_data, TELNET_TIMEOUT)
myrouter.connect(args.verbose)
myrouter.nopaging(args.verbose)
if args.output:
output1 = open(args.output, 'w')
for addr in addr_range:
full_cmd = ROUTER_CMD + ' ' + str(addr)
print 'Processing {}...'.format(full_cmd)
output = myrouter.sendcmd(full_cmd, args.verbose)
# output has extra carriage returns - remove
new_output = output.replace('\r', '')
result = 'Command ({}) output:\n{}\n'.format(full_cmd, new_output)
if args.output:
output1.write(result)
output1.write('\n')
else:
print result
# Cleanup
myrouter.connection.close()
if args.output:
output1.close()
示例3: validate_ip_addr
def validate_ip_addr(addr, version=None):
"""
Validates that an IP address is valid. Returns true if valid, false if
not. Version can be "4", "6", None for "IPv4", "IPv6", or "either"
respectively.
"""
if version == 4:
return netaddr.valid_ipv4(addr)
elif version == 6:
return netaddr.valid_ipv6(addr)
else:
return netaddr.valid_ipv4(addr) or netaddr.valid_ipv6(addr)
示例4: _is_ip
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)
示例5: get_common_server
def get_common_server(self):
data = {
'public_address': None,
'private_address': None,
'service_net_name_or_ip': self.get_config_option(
'service_net_name_or_ip'),
'tenant_net_name_or_ip': self.get_config_option(
'tenant_net_name_or_ip'),
}
data['instance'] = self.compute_api.server_get_by_name_or_id(
self.admin_context,
self.get_config_option('service_instance_name_or_id'))
if netaddr.valid_ipv4(data['service_net_name_or_ip']):
data['private_address'] = [data['service_net_name_or_ip']]
else:
data['private_address'] = self._get_addresses_by_network_name(
data['service_net_name_or_ip'], data['instance'])
if netaddr.valid_ipv4(data['tenant_net_name_or_ip']):
data['public_address'] = [data['tenant_net_name_or_ip']]
else:
data['public_address'] = self._get_addresses_by_network_name(
data['tenant_net_name_or_ip'], data['instance'])
if not (data['public_address'] and data['private_address']):
raise exception.ManilaException(
"Can not find one of net addresses for service instance. "
"Instance: %(instance)s, "
"private_address: %(private_address)s, "
"public_address: %(public_address)s." % data)
share_server = {
'username': self.get_config_option('service_instance_user'),
'password': self.get_config_option('service_instance_password'),
'pk_path': self.path_to_private_key,
'instance_id': data['instance']['id'],
}
for key in ('private_address', 'public_address'):
data[key + '_v4'] = None
for address in data[key]:
if netaddr.valid_ipv4(address):
data[key + '_v4'] = address
break
share_server['ip'] = data['private_address_v4']
share_server['public_address'] = data['public_address_v4']
return {'backend_details': share_server}
示例6: is_ip
def is_ip(self, ip_addr=None):
"""
Return true if valid IP address return false if invalid IP address
:param ip_addr: optional IP to pass. Takes from root class if not specified
>>> from ipinformation import IPInformation
>>> print IPInformation(ip_address='8.8.8.8').is_ip()
True
>>> print IPInformation(ip_address='NotAnIP').is_ip()
False
"""
if not ip_addr:
ip_addr = self.ip_address
valid = True
if netaddr.valid_ipv4(ip_addr): # IPv4 Address
if not re.match(valid_ip_regex, ip_addr):
valid = False
elif netaddr.valid_ipv6(ip_addr):
pass
else:
# print '"%s" is not a valid IP Address.' %ip_addr
valid = False
return valid
示例7: _connect_tcp
def _connect_tcp(self, peer_addr, conn_handler, time_out=None,
bind_address=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 = hub.connect(peer_addr, family=family, bind=bind_address)
if sock:
# Connection name for pro-active connection is made up
# of local end address + remote end address
conn_name = ('L: ' + str(sock.getsockname()) + ', R: ' +
str(sock.getpeername()))
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
示例8: _get_address_groups
def _get_address_groups(self, context, network_id, device_id, is_proxy):
filters = {'network_id': [network_id],
'device_id': [device_id]}
ports = self.nsxv_plugin.get_ports(context, filters=filters)
subnets = self.nsxv_plugin.get_subnets(context, filters=filters)
address_groups = []
for subnet in subnets:
address_group = {}
net = netaddr.IPNetwork(subnet['cidr'])
address_group['subnetMask'] = str(net.netmask)
address_group['subnetPrefixLength'] = str(net.prefixlen)
for port in ports:
fixed_ips = port['fixed_ips']
for fip in fixed_ips:
s_id = fip['subnet_id']
ip_addr = fip['ip_address']
if s_id == subnet['id'] and netaddr.valid_ipv4(ip_addr):
address_group['primaryAddress'] = ip_addr
break
# For Edge appliances which aren't the metadata proxy Edge
# we add the metadata IP address
if not is_proxy and network_id == self.internal_net:
address_group['secondaryAddresses'] = {
'type': 'secondary_addresses',
'ipAddress': [METADATA_IP_ADDR]}
address_groups.append(address_group)
return address_groups
示例9: prefix_add
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())
call(func_name, **networks)
示例10: add_to_global_table
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)
示例11: get_ipv6_addr_by_EUI64
def get_ipv6_addr_by_EUI64(prefix, mac):
"""Calculate IPv6 address using EUI-64 specification.
This method calculates the IPv6 address using the EUI-64
addressing scheme as explained in rfc2373.
:param prefix: IPv6 prefix.
:param mac: IEEE 802 48-bit MAC address.
:returns: IPv6 address on success.
:raises ValueError, TypeError: For any invalid input.
.. versionadded:: 1.4
"""
# Check if the prefix is an IPv4 address
if netaddr.valid_ipv4(prefix):
msg = _("Unable to generate IP address by EUI64 for IPv4 prefix")
raise ValueError(msg)
try:
eui64 = int(netaddr.EUI(mac).eui64())
prefix = netaddr.IPNetwork(prefix)
return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
except (ValueError, netaddr.AddrFormatError):
raise ValueError(_('Bad prefix or mac format for generating IPv6 '
'address by EUI-64: %(prefix)s, %(mac)s:')
% {'prefix': prefix, 'mac': mac})
except TypeError:
raise TypeError(_('Bad prefix type for generating IPv6 address by '
'EUI-64: %s') % prefix)
示例12: _connect_tcp
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 raised in case 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
示例13: create_connection
def create_connection(address):
"""
Wrapper for socket.create_connection() function.
If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6
address, passes *address* to socket.create_connection().
If *host* is valid path to Unix Domain socket, tries to connect to
the server listening on the given socket.
:param address: IP address or path to Unix Domain socket.
:return: Socket instance.
"""
host, _port = address
if (netaddr.valid_ipv4(host)
or netaddr.valid_ipv6(host)):
return socket.create_connection(address)
elif os.path.exists(host):
sock = None
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(host)
except socket.error as e:
if sock is not None:
sock.close()
raise e
return sock
else:
raise ValueError('Invalid IP address or Unix Socket: %s' % host)
示例14: neighbor_add
def neighbor_add(self, address, remote_as,
enable_ipv4=DEFAULT_CAP_MBGP_IPV4,
enable_vpnv4=DEFAULT_CAP_MBGP_VPNV4,
enable_vpnv6=DEFAULT_CAP_MBGP_VPNV6,
next_hop=None, password=None, multi_exit_disc=None):
""" This method registers a new neighbor. The BGP speaker tries to
establish a bgp session with the peer (accepts a connection
from the peer and also tries to connect to it).
``address`` specifies the IP address of the peer. It must be
the string representation of an IP address. Only IP v4 is
supported now.
``remote_as`` specifies the AS number of the peer. It must be
an integer between 1 and 65535.
``enable_ipv4`` enables IPv4 address family for this
neighbor. The default is True.
``enable_vpnv4`` enables VPNv4 address family for this
neighbor. The default is False.
``enable_vpnv6`` enables VPNv6 address family for this
neighbor. The default is False.
``next_hop`` specifies the next hop IP address. If not
specified, host's ip address to access to a peer is used.
``password`` is used for the MD5 authentication if it's
specified. By default, the MD5 authenticaiton is disabled.
``multi_exit_disc`` specifies multi exit discriminator (MED) value.
The default is None and if not specified, MED value is
not sent to the neighbor. It must be an integer.
"""
bgp_neighbor = {}
bgp_neighbor[neighbors.IP_ADDRESS] = address
bgp_neighbor[neighbors.REMOTE_AS] = remote_as
bgp_neighbor[PEER_NEXT_HOP] = next_hop
bgp_neighbor[PASSWORD] = password
# v6 advertizement is available with only v6 peering
if netaddr.valid_ipv4(address):
bgp_neighbor[CAP_MBGP_IPV4] = enable_ipv4
bgp_neighbor[CAP_MBGP_IPV6] = False
bgp_neighbor[CAP_MBGP_VPNV4] = enable_vpnv4
bgp_neighbor[CAP_MBGP_VPNV6] = enable_vpnv6
elif netaddr.valid_ipv6(address):
bgp_neighbor[CAP_MBGP_IPV4] = False
bgp_neighbor[CAP_MBGP_IPV6] = True
bgp_neighbor[CAP_MBGP_VPNV4] = False
bgp_neighbor[CAP_MBGP_VPNV6] = False
else:
# FIXME: should raise an exception
pass
if multi_exit_disc:
bgp_neighbor[MULTI_EXIT_DISC] = multi_exit_disc
call('neighbor.create', **bgp_neighbor)
示例15: _handle_host_snat_ip
def _handle_host_snat_ip(self, host_snat_ips):
for hsi in host_snat_ips:
LOG.debug(_("Auto-allocated host SNAT IP: %s"), hsi)
es = hsi.get('external_segment_name')
if not es:
continue
nh = self.ext_seg_next_hop.setdefault(es, ExtSegNextHopInfo(es))
if nh.from_config:
continue # ignore auto-allocation if manually set
ip = hsi.get('host_snat_ip')
gw = ("%s/%s" % (hsi['gateway_ip'], hsi['prefixlen'])
if (hsi.get('gateway_ip') and hsi.get('prefixlen')) else None)
updated = False
if netaddr.valid_ipv4(ip):
if ip != nh.ip_start or gw != nh.ip_gateway:
nh.ip_start = ip
nh.ip_gateway = gw
updated = True
elif netaddr.valid_ipv6(ip):
if ip != nh.ip6_start or gw != nh.ip6_gateway:
nh.ip6_start = ip
nh.ip6_gateway = gw
updated = True
else:
LOG.info(_("Ignoring invalid auto-allocated SNAT IP %s"), ip)
if updated:
# Clear the interface so that SNAT iptables will be
# re-created as required; leave MAC as is so that it will
# be re-used
nh.next_hop_iface = None
LOG.info(_("Add/update SNAT info: %s"), nh)