Python netaddr.valid_mac() Examples

The following are 9 code examples for showing how to use netaddr.valid_mac(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module netaddr , or try the search function .

Example 1
Project: neutron-lib   Author: openstack   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def validate_mac_address(data, valid_values=None):
    """Validate data is a MAC address.

    :param data: The data to validate.
    :param valid_values: Not used!
    :returns: None if the data is a valid MAC address, otherwise a human
        readable message as to why validation failed.
    """
    try:
        valid_mac = netaddr.valid_mac(validate_no_whitespace(data))
    except Exception:
        valid_mac = False

    if valid_mac:
        valid_mac = (not netaddr.EUI(data) in
                     map(netaddr.EUI, constants.INVALID_MAC_ADDRESSES))
    # TODO(arosen): The code in this file should be refactored
    # so it catches the correct exceptions. validate_no_whitespace
    # raises AttributeError if data is None.
    if not valid_mac:
        msg = _("'%s' is not a valid MAC address") % data
        LOG.debug(msg)
        return msg 
Example 2
Project: dragonflow   Author: openstack   File: vswitch_impl.py    License: Apache License 2.0 5 votes vote down vote up
def get_local_port_mac_in_use(self, port_id):
        iface = self.get_interface_by_id_with_specified_columns(
            port_id, {'mac_in_use'})
        if iface and netaddr.valid_mac(iface['mac_in_use']):
            return iface['mac_in_use'] 
Example 3
Project: tacker   Author: openstack   File: validators.py    License: Apache License 2.0 5 votes vote down vote up
def validate_mac_address_or_none(instance):
    """Validate instance is a MAC address"""

    if instance is None:
        return

    if not netaddr.valid_mac(instance):
        msg = _("'%s' is not a valid mac address")
        raise webob.exc.HTTPBadRequest(explanation=msg % instance)

    return True 
Example 4
Project: tacker   Author: openstack   File: attributes.py    License: Apache License 2.0 5 votes vote down vote up
def _validate_mac_address(data, valid_values=None):
    try:
        valid_mac = netaddr.valid_mac(_validate_no_whitespace(data))
        if valid_mac is False:
            msg = _("'%s' is not a valid MAC address") % data
            LOG.debug(msg)
            return msg
    except AttributeError as ex:
        msg = _("MAC address must be string: %s") % ex
        LOG.exception(msg)
        return msg 
Example 5
Project: faucet   Author: faucetsdn   File: dp.py    License: Apache License 2.0 5 votes vote down vote up
def check_config(self):
        """Check configuration of this dp"""
        super(DP, self).check_config()
        test_config_condition(not isinstance(self.dp_id, int), (
            'dp_id must be %s not %s' % (int, type(self.dp_id))))
        test_config_condition(self.dp_id < 0 or self.dp_id > 2**64-1, (
            'DP ID %s not in valid range' % self.dp_id))
        test_config_condition(not netaddr.valid_mac(self.faucet_dp_mac), (
            'invalid MAC address %s' % self.faucet_dp_mac))
        test_config_condition(not (self.interfaces or self.interface_ranges), (
            'DP %s must have at least one interface' % self))
        test_config_condition(self.timeout < 15, 'timeout must be > 15')
        test_config_condition(self.timeout > 65535, 'timeout cannot be > than 65335')
        # To prevent L2 learning from timing out before L3 can refresh
        test_config_condition(not (self.arp_neighbor_timeout < (self.timeout / 2)), (
            'L2 timeout must be > ARP timeout * 2'))
        test_config_condition(
            self.arp_neighbor_timeout > 65535, 'arp_neighbor_timeout cannot be > 65535')
        test_config_condition(not (self.nd_neighbor_timeout < (self.timeout / 2)), (
            'L2 timeout must be > ND timeout * 2'))
        test_config_condition(
            self.nd_neighbor_timeout > 65535, 'nd_neighbor_timeout cannot be > 65535')
        test_config_condition(self.combinatorial_port_flood and self.group_table, (
            'combinatorial_port_flood and group_table mutually exclusive'))
        if self.cache_update_guard_time == 0:
            self.cache_update_guard_time = int(self.timeout / 2)
        if self.learn_jitter == 0:
            self.learn_jitter = int(max(math.sqrt(self.timeout) * 3, 1))
        if self.learn_ban_timeout == 0:
            self.learn_ban_timeout = self.learn_jitter
        if self.stack:
            self._check_conf_types(self.stack, self.stack_defaults_types)
        if self.lldp_beacon:
            self._lldp_defaults()
        if self.dot1x:
            self._check_conf_types(self.dot1x, self.dot1x_defaults_types)
        self._check_conf_types(self.table_sizes, self.default_table_sizes_types) 
Example 6
Project: neutron-lib   Author: openstack   File: test_conversions.py    License: Apache License 2.0 5 votes vote down vote up
def test_mac_address_does_not_convert(self):
        valid_mac = 'fa:16:3e:b6:78:1f'
        self.assertEqual(valid_mac,
                         converters.convert_to_mac_if_none(valid_mac)) 
Example 7
Project: neutron-lib   Author: openstack   File: test_conversions.py    License: Apache License 2.0 5 votes vote down vote up
def test_convert_none_to_mac_address(self, CONF):
        CONF.base_mac = 'fa:16:3e:00:00:00'
        self.assertTrue(
            netaddr.valid_mac(converters.convert_to_mac_if_none(None))) 
Example 8
Project: faucet   Author: faucetsdn   File: vlan.py    License: Apache License 2.0 4 votes vote down vote up
def check_config(self):
        super(VLAN, self).check_config()
        test_config_condition(not self.vid_valid(self.vid), 'invalid VID %s' % self.vid)
        test_config_condition(not netaddr.valid_mac(self.faucet_mac), (
            'invalid MAC address %s' % self.faucet_mac))

        test_config_condition(
            self.acl_in and self.acls_in, 'found both acl_in and acls_in, use only acls_in')
        test_config_condition(
            self.acl_out and self.acls_out, 'found both acl_out and acls_out, use only acls_out')
        if self.acl_in and not isinstance(self.acl_in, list):
            self.acls_in = [self.acl_in,]
            self.acl_in = None
        if self.acl_out and not isinstance(self.acl_out, list):
            self.acls_out = [self.acl_out,]
            self.acl_out = None
        all_acls = []
        if self.acls_in:
            all_acls.extend(self.acls_in)
        if self.acls_out:
            all_acls.extend(self.acls_out)
        for acl in all_acls:
            test_config_condition(
                not isinstance(acl, (int, str)), 'acl names must be int or str')

        if self.max_hosts:
            if not self.proactive_arp_limit:
                self.proactive_arp_limit = 2 * self.max_hosts
            if not self.proactive_nd_limit:
                self.proactive_nd_limit = 2 * self.max_hosts

        if self.faucet_vips:
            self.faucet_vips = frozenset([
                self._check_ip_str(ip_str, ip_method=ipaddress.ip_interface)
                for ip_str in self.faucet_vips])
            for faucet_vip in self.faucet_vips:
                test_config_condition(
                    faucet_vip.network.prefixlen == faucet_vip.max_prefixlen,
                    'VIP cannot be a host address')

        if self.routes:
            test_config_condition(not isinstance(self.routes, list), 'invalid VLAN routes format')
            try:
                self.routes = [route['route'] for route in self.routes]
            except TypeError:
                raise InvalidConfigError('%s is not a valid routes value' % self.routes)
            except KeyError:
                pass
            for route in self.routes:
                test_config_condition(not isinstance(route, dict), 'invalid VLAN route format')
                test_config_condition('ip_gw' not in route, 'missing ip_gw in VLAN route')
                test_config_condition('ip_dst' not in route, 'missing ip_dst in VLAN route')
                ip_gw = self._check_ip_str(route['ip_gw'])
                ip_dst = self._check_ip_str(route['ip_dst'], ip_method=ipaddress.ip_network)
                test_config_condition(
                    ip_gw.version != ip_dst.version,
                    'ip_gw version does not match the ip_dst version')
                self.add_route(ip_dst, ip_gw) 
Example 9
Project: netscan2   Author: AllGloryToTheHypnotoad   File: lib.py    License: MIT License 4 votes vote down vote up
def get(self, mac, full):
        """
        json response from www.macvendorlookup.com:

        {u'addressL1': u'1 Infinite Loop',
        u'addressL2': u'',
        u'addressL3': u'Cupertino CA 95014',
        u'company': u'Apple',
        u'country': u'UNITED STATES',
        u'endDec': u'202412195315711',
        u'endHex': u'B817C2FFFFFF',
        u'startDec': u'202412178538496',
        u'startHex': u'B817C2000000',
        u'type': u'MA-L'}
        """
        unknown = {'company': 'unknown'}
        if not valid_mac(mac):
            print('Error: the mac addr {} is not valid'.format(mac))
            return

        try:
            r = requests.get('http://www.macvendorlookup.com/api/v2/' + mac)
        except requests.exceptions.HTTPError as e:
            print ("HTTPError:", e.message)
            return unknown

        if r.status_code == 204:  # no content found, bad MAC addr
            print ('ERROR: Bad MAC addr:', mac)
            return unknown
        elif r.headers['content-type'] != 'application/json':
            print ('ERROR: Wrong content type:', r.headers['content-type'])
            return unknown

        a = {}

        try:
            if full: a = r.json()[0]
            else: a['company'] = r.json()[0]['company']
            # print 'GOOD:',r.status_code,r.headers,r.ok,r.text,r.reason
        except:
            print ('ERROR:', r.status_code, r.headers, r.ok, r.text, r.reason)
            a = unknown

        return a