File: mac.py

package info (click to toggle)
python-os-ken 3.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 21,280 kB
  • sloc: python: 100,620; erlang: 14,517; ansic: 594; sh: 338; makefile: 136
file content (66 lines) | stat: -rw-r--r-- 1,853 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from os_ken.lib import addrconv
import struct

# string representation
HADDR_PATTERN = r'([0-9a-f]{2}:){5}[0-9a-f]{2}'

DONTCARE = b'\x00' * 6
BROADCAST = b'\xff' * 6
DONTCARE_STR = '00:00:00:00:00:00'
BROADCAST_STR = 'ff:ff:ff:ff:ff:ff'
MULTICAST = 'fe:ff:ff:ff:ff:ff'
UNICAST = '01:00:00:00:00:00'


def is_multicast(addr):
    return bool(int(addr[0]) & 0x01)


def haddr_to_str(addr):
    """Format mac address in internal representation into human readable
    form"""
    if addr is None:
        return 'None'
    try:
        return addrconv.mac.bin_to_text(addr)
    except:
        raise AssertionError


def haddr_to_int(addr):
    """Convert mac address string in human readable format into
    integer value"""
    try:
        return int(addr.replace(':', ''), 16)
    except:
        raise ValueError


def haddr_to_bin(string):
    """Parse mac address string in human readable format into
    internal representation"""
    try:
        return addrconv.mac.text_to_bin(string)
    except:
        raise ValueError


def haddr_bitand(addr, mask):
    return b''.join(struct.Struct(">B").pack(int(a) & int(m)) for (a, m)
                    in zip(addr, mask))