The Pedigree Project 0.1
MacAddress.cc
1/*
2 * Copyright (c) 2008-2014, Pedigree Developers
3 *
4 * Please see the CONTRIB file in the root of the source tree for a full
5 * list of contributors.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include "pedigree/kernel/network/MacAddress.h"
21#include "pedigree/kernel/utilities/StaticString.h"
22#include "pedigree/kernel/utilities/utility.h"
23
24MacAddress::MacAddress() : m_Mac(), m_Valid(false) {
25 ByteSet(m_Mac, 0, 6);
26}
27
28MacAddress::MacAddress(const MacAddress& other) : MacAddress() {
29 m_Valid = other.valid();
30 if (other.valid()) {
31 setMac(other.getMac());
32 }
33}
34
35void MacAddress::setMac(uint8_t byte, size_t element) {
36 uint16_t word = byte;
37 if (element % 2) {
38 word <<= 8;
39 }
40
41 element /= 2;
42
43 if (element < 3) {
44 m_Mac[element] |= word;
45 m_Valid = true; // it has at least a byte, which makes it partially valid
46 }
47}
48
49void MacAddress::setMac(uint8_t element) {
50 ByteSet(m_Mac, element, 6);
51 m_Valid = true;
52}
53
54void MacAddress::setMac(const uint16_t* data, bool bSwap) {
55 if (bSwap) {
56 size_t i;
57 for (i = 0; i < 3; i++)
58 m_Mac[i] = BIG_TO_HOST16(data[i]);
59 } else
60 MemoryCopy(m_Mac, data, 6);
61
62 m_Valid = true;
63};
64
65uint8_t MacAddress::getMac(size_t element) const {
66 size_t realElement = element / 2;
67 if (realElement >= 3)
68 return 0;
69
70 uint16_t word = m_Mac[realElement];
71 if (element % 2)
72 return word >> 8;
73 else
74 return word & 0xFF;
75};
76
77const uint16_t* MacAddress::getMac() const {
78 return m_Mac;
79};
80
81uint8_t MacAddress::operator[](size_t offset) const {
82 if (m_Valid)
83 return getMac(offset);
84 else
85 return 0;
86};
87
88MacAddress& MacAddress::operator=(const MacAddress& a) {
89 if (a.valid())
90 setMac(a.getMac());
91 return *this;
92}
93
94MacAddress& MacAddress::operator=(const uint16_t* a) {
95 setMac(a);
96 return *this;
97}
98
99String MacAddress::toString() {
101 for (int i = 0; i < 6; i++) {
102 str.append(getMac(i), 16, 2, '0');
103 if (i < 5)
104 str += ":";
105 }
106 return String(static_cast<const char*>(str));
107}