Python netaddr.valid_ipv4() Examples

The following are 24 code examples of netaddr.valid_ipv4(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module netaddr , or try the search function .
Example #1
Source File: data_utils.py    From tempest-lib with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: lib.py    From netscan2 with MIT License 6 votes vote down vote up
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 
Example #3
Source File: utils.py    From python-tripleoclient with Apache License 2.0 5 votes vote down vote up
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) 
Example #4
Source File: netutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def is_valid_ipv4(address):
    """Verify that address represents a valid IPv4 address.

    :param address: Value to verify
    :type address: string
    :returns: bool

    .. versionadded:: 1.1
    """
    try:
        return netaddr.valid_ipv4(address)
    except netaddr.AddrFormatError:
        return False 
Example #5
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_valid_ip(ip):
    """Check the validity of an IP address."""
    return valid_ipv4(ip) or valid_ipv6(ip) 
Example #6
Source File: ipaddr.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv4(ip):
    try:
        return netaddr.valid_ipv4(ip)
    except:
        return False 
Example #7
Source File: squidFixup.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv4(self, ip):
        try:
            return valid_ipv4(ip)
        except:
            return False 
Example #8
Source File: ipFixup.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv4(ip):
    try:
        return netaddr.valid_ipv4(ip)
    except:
        return False 
Example #9
Source File: lib.py    From netscan2 with MIT License 5 votes vote down vote up
def __init__(self, ip):
        """Use the avahi (zeroconfig) tools or dig to find a host name given an
        ip address.

        in: ip
        out: string w/ host name or 'unknown' if the host name couldn't be found
        """
        # handle invalid ip address
        if not valid_ipv4(ip):
            print('Error: the IPv4 address {} is invalid'.format(ip))
            return

        # handle a localhost ip address
        if ip == '127.0.0.1' or ip == 'localhost':
            # self.name = platform.node()
            self.name = socket.gethostname()
            return

        # ok, now do more complex stuff
        name = 'unknown'
        if sys.platform == 'linux' or sys.platform == 'linux2':
            name = self.command("avahi-resolve-address {} | awk '{print $2}'".format(ip)).rstrip().rstrip('.')
        elif sys.platform == 'darwin':
            name = self.command('dig +short -x {} -p 5353 @224.0.0.251'.format(ip)).rstrip().rstrip('.')

        # detect any remaining errors
        if name.find('connection timed out') >= 0:
            name = 'unknown'
        elif name == '':
            name = 'unknown'

        self.name = name

    # def cmdLine(self, cmd):
    #     return subprocess.Popen([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()[0] 
Example #10
Source File: roku.py    From netscan2 with MIT License 5 votes vote down vote up
def get_host_name(ip):
    """
    Use the avahi (zeroconfig) tools or dig to find a host name given an
    ip address.

    in: ip
    out: string w/ host name or 'unknown' if the host name couldn't be found
    """
    # ret = None
    # handle invalid ip address
    if not valid_ipv4(ip):
        print('Error: the IPv4 address {} is invalid'.format(ip))
        return 'unknown'

    # handle a localhost ip address
    if ip == '127.0.0.1' or ip == 'localhost':
        return socket.gethostname()

    # ok, now do more complex stuff
    if sys.platform == 'linux' or sys.platform == 'linux2':
        name = command("avahi-resolve-address {} | awk '{print $2}'".format(ip)).rstrip().rstrip('.')
    elif sys.platform == 'darwin':
        name = command('dig +short -x {} -p 5353 @224.0.0.251'.format(ip)).rstrip().rstrip('.')
    else:
        raise Exception("get_host_name is unsupported on your OS, get a better one :)")

    # detect any remaining errors
    if name.find('connection timed out') >= 0 or len(name) == 0:
        name = 'unknown'

    return name 
Example #11
Source File: roku.py    From netscan2 with MIT License 5 votes vote down vote up
def whois(ip):
    """
    Given a valid ipv4 address, it returns the whois info as a namedtuple:

    whois('172.217.12.4')
    HostInfo(cidr=u'172.217.0.0/16', netname=u'GOOGLE', netrange=u'172.217.0.0 - 172.217.255.255', org=u'Google LLC (GOGL)', updated=u'2012-04-16')
    """
    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 i, s in enumerate(b):
        if len(s) == 0:
            b.pop(i)
        elif s[0] == u'#':
            b.pop(i)
    print('---------')
    print(b)
    for l in b:
        if l and l[0] != '#':
            l = r.sub('', l)
            a = l.split(':')
            ans[a[0]] = a[1]

    return HostInfo(
        ans['CIDR'],
        ans['NetName'],
        ans['NetRange'],
        ans['Organization'],
        ans['Updated']) 
Example #12
Source File: helpers.py    From Loki with GNU General Public License v3.0 5 votes vote down vote up
def is_ip(string):
    try:
        if netaddr.valid_ipv4(string):
            return True
        if netaddr.valid_ipv6(string):
            return True
        return False
    except:
        traceback.print_exc()
        return False 
Example #13
Source File: utils.py    From tacker with Apache License 2.0 5 votes vote down vote up
def is_valid_ipv4(address):
    """Verify that address represents a valid IPv4 address."""
    try:
        return netaddr.valid_ipv4(address)
    except Exception:
        return False 
Example #14
Source File: validator.py    From ec2-api with Apache License 2.0 5 votes vote down vote up
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')) 
Example #15
Source File: software_hosts.py    From power-up with Apache License 2.0 5 votes vote down vote up
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 
Example #16
Source File: ip_route_get_to.py    From power-up with Apache License 2.0 5 votes vote down vote up
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 
Example #17
Source File: crossdomain.py    From xpire-crossdomain-scanner with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #18
Source File: bgpspeaker.py    From ryu with Apache License 2.0 5 votes vote down vote up
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) 
Example #19
Source File: neighbors.py    From ryu with Apache License 2.0 5 votes vote down vote up
def valid_ip_address(addr):
    if not netaddr.valid_ipv4(addr) and not netaddr.valid_ipv6(addr):
        return False
    return True 
Example #20
Source File: core.py    From ryu with Apache License 2.0 5 votes vote down vote up
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) 
Example #21
Source File: base.py    From ryu with Apache License 2.0 5 votes vote down vote up
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
# 
Example #22
Source File: table_manager.py    From ryu with Apache License 2.0 5 votes vote down vote up
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) 
Example #23
Source File: utils.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
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') 
Example #24
Source File: vpn_connection.py    From ec2-api with Apache License 2.0 5 votes vote down vote up
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']}