How to use the netaddr.core function in netaddr

To help you get started, we’ve selected a few netaddr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PaloAltoNetworks / minemeld-core / minemeld / ft / dag.py View on Github external
self.name, type_)
            self.statistics['ignored'] += 1
            return

        if '-' in indicator:
            i1, i2 = indicator.split('-', 1)
            if i1 != i2:
                LOG.error('%s - indicator range must be equal, ignored: %s',
                          self.name, indicator)
                self.statistics['ignored'] += 1
                return
            indicator = i1

        try:
            address = netaddr.IPNetwork(indicator)
        except netaddr.core.AddrFormatError as e:
            LOG.error('%s - invalid IP address received, ignored: %s',
                      self.name, e)
            self.statistics['ignored'] += 1
            return

        if address.size != 1:
            LOG.error('%s - IP network received, ignored: %s',
                      self.name, address)
            self.statistics['ignored'] += 1
            return

        if type_ == 'IPv4' and address.version != 4 or \
           type_ == 'IPv6' and address.version != 6:
            LOG.error('%s - IP version mismatch, ignored',
                      self.name)
            self.statistics['ignored'] += 1
github oldkingcone / Albert / auto_albert.py View on Github external
async def subnet_discover(ip):
        import netaddr
        try:
            question = netaddr.IPAddress(ip)
            response = netaddr.IPNetwork(ip).cidr
            print("Reverse DNS {}".format(question.reverse_dns))
            print("Subnet/CIDR: {}".format(response.cidr))
            print("Private? {}".format(question.is_private))
            print("Net Mask: {}".format(response.netmask))
            print("Broad Cast: {}".format(response.broadcast))
            print("Host Mask: {}".format(response.hostmask))
            print("Multicast: {}".format(question.is_multicast))
            return response
        except netaddr.core.AddrFormatError as es:
            print("[✘] Sorry, that was not an IP [✘] \n\t\t-> {}".format(es))
            return es
github opencomputeproject / OpenNetworkLinux / packages / base / all / vendor-config-onl / src / python / onl / bootconfig / __init__.py View on Github external
    @staticmethod
    def is_netmask(value):
        try:
            if not netaddr.IPAddress(value).is_netmask():
                return False
            return value
        except (netaddr.core.AddrFormatError, ValueError):
            return False
github romana / vpc-router / vpcrouter / utils / __init__.py View on Github external
def ip_check(ip, netmask_expected=False):
    """
    Sanity check that the specified string is indeed an IP address or mask.

    """
    try:
        if netmask_expected:
            if "/" not in ip:
                raise netaddr.core.AddrFormatError()
            netaddr.IPNetwork(ip)
        else:
            netaddr.IPAddress(ip)
    except netaddr.core.AddrFormatError:
        if netmask_expected:
            raise ArgsError("Not a valid CIDR (%s)" % ip)
        else:
            raise ArgsError("Not a valid IP address (%s)" % ip)
    except Exception as e:
        raise ArgsError("Invalid format: %s" % str(e))
github mozilla / MozDef / alerts / proxy_drop_ip.py View on Github external
category = "squid"
        tags = ["squid", "proxy"]
        severity = "WARNING"

        dropped_destinations = set()
        final_aggr = {}
        final_aggr["value"] = aggreg["value"]
        final_aggr["allevents"] = []
        final_aggr["events"] = []

        i = 0
        for event in aggreg["allevents"]:
            ip = None
            try:
                ip = netaddr.IPAddress(event["_source"]["details"]["host"])
            except (netaddr.core.AddrFormatError, ValueError):
                pass
            if ip is not None:
                dropped_destinations.add(event["_source"]["details"]["host"])
                final_aggr["allevents"].append(event)
                final_aggr["events"].append(event)
                i += i
        final_aggr["count"] = i

        # If it's all over-matches, don't throw the alert
        if len(dropped_destinations) == 0:
            return None

        summary = "Suspicious Proxy DROP event(s) detected from {0} to the following IP-based destination(s): {1}".format(
            final_aggr["value"], ",".join(sorted(dropped_destinations))
        )
github projectcalico / felix / python / calico / common.py View on Github external
def validate_cidr(cidr, version):
    """
    Validates that a CIDR is valid. Returns true if valid, false if
    not. Version can be "4", "6", None for "IPv4", "IPv6", or "either"
    respectively.
    """
    try:
        ip = netaddr.IPNetwork(cidr, version=version)
        return True
    except (netaddr.core.AddrFormatError, ValueError, TypeError):
        return False
github k4yt3x / wireguard-mesh-configurator / src / profilemanager.py View on Github external
peer_config['Address'] = address = str(netaddr.IPNetwork(address))
            except netaddr.core.AddrFormatError:
                Avalon.error('Invalid address entered')
                Avalon.error('Please use CIDR notation (e.g. 10.0.0.0/8)')
                continue
            break

        # Get peer public IP address
        while True:
            public_address = Avalon.gets('Public address (leave empty if client only) [IP|FQDN]: ')

            # check if public_address is valid IP or FQDN
            valid_address = False

            # check if input is valid IPv4/IPv6 address
            with contextlib.suppress(netaddr.core.AddrFormatError):
                netaddr.IPAddress(public_address)
                valid_address = True

            # check if input is valid FQDN
            if re.match('(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?
github sk2 / autonetkit / autonetkit / ank_json.py View on Github external
def string_to_netaddr(val):
    retval = None
    dot_count = string.count(val, ".")
    if dot_count:
        # could be an IP or network address
        if "/" in val:
            try:
                retval = netaddr.IPNetwork(val)
            except netaddr.core.AddrFormatError:
                return  # unable to convert, leave as string
        else:
            try:
                retval = netaddr.IPAddress(val)
            except netaddr.core.AddrFormatError:
                return  # unable to convert, leave as string

    return retval
github romana / vpc-router / vpcrouter / utils / __init__.py View on Github external
def ip_check(ip, netmask_expected=False):
    """
    Sanity check that the specified string is indeed an IP address or mask.

    """
    try:
        if netmask_expected:
            if "/" not in ip:
                raise netaddr.core.AddrFormatError()
            netaddr.IPNetwork(ip)
        else:
            netaddr.IPAddress(ip)
    except netaddr.core.AddrFormatError:
        if netmask_expected:
            raise ArgsError("Not a valid CIDR (%s)" % ip)
        else:
            raise ArgsError("Not a valid IP address (%s)" % ip)
    except Exception as e:
        raise ArgsError("Invalid format: %s" % str(e))
github openstack / neutron / neutron / db / db_base_plugin_v2.py View on Github external
def _validate_host_route(self, route, ip_version):
        try:
            netaddr.IPNetwork(route['destination'])
            netaddr.IPAddress(route['nexthop'])
        except netaddr.core.AddrFormatError:
            err_msg = _("Invalid route: %s") % route
            raise exc.InvalidInput(error_message=err_msg)
        except ValueError:
            # netaddr.IPAddress would raise this
            err_msg = _("Invalid route: %s") % route
            raise exc.InvalidInput(error_message=err_msg)
        self._validate_ip_version(ip_version, route['nexthop'], 'nexthop')
        self._validate_ip_version(ip_version, route['destination'],
                                  'destination')