Statistics
| Branch: | Tag: | Revision:

root / host / lib / types / mac_addr.cpp @ caff65d7

History | View | Annotate | Download (2.26 KB)

1
//
2
// Copyright 2011 Ettus Research LLC
3
//
4
// This program is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// This program is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
//
17

    
18
#include <uhd/types/mac_addr.hpp>
19
#include <uhd/exception.hpp>
20
#include <boost/tokenizer.hpp>
21
#include <boost/foreach.hpp>
22
#include <boost/format.hpp>
23
#include <boost/cstdint.hpp>
24
#include <sstream>
25

    
26
using namespace uhd;
27

    
28
mac_addr_t::mac_addr_t(const byte_vector_t &bytes) : _bytes(bytes){
29
    UHD_ASSERT_THROW(_bytes.size() == 6);
30
}
31

    
32
mac_addr_t mac_addr_t::from_bytes(const byte_vector_t &bytes){
33
    return mac_addr_t(bytes);
34
}
35

    
36
mac_addr_t mac_addr_t::from_string(const std::string &mac_addr_str){
37

    
38
    byte_vector_t bytes;
39

    
40
    try{
41
        if (mac_addr_str.size() != 17){
42
            throw uhd::value_error("expected exactly 17 characters");
43
        }
44

    
45
        //split the mac addr hex string at the colons
46
        boost::tokenizer<boost::char_separator<char> > hex_num_toks(
47
            mac_addr_str, boost::char_separator<char>(":"));
48
        BOOST_FOREACH(const std::string &hex_str, hex_num_toks){
49
            int hex_num;
50
            std::istringstream iss(hex_str);
51
            iss >> std::hex >> hex_num;
52
            bytes.push_back(boost::uint8_t(hex_num));
53
        }
54

    
55
    }
56
    catch(std::exception const& e){
57
        throw uhd::value_error(str(
58
            boost::format("Invalid mac address: %s\n\t%s") % mac_addr_str % e.what()
59
        ));
60
    }
61

    
62
    return mac_addr_t::from_bytes(bytes);
63
}
64

    
65
byte_vector_t mac_addr_t::to_bytes(void) const{
66
    return _bytes;
67
}
68

    
69
std::string mac_addr_t::to_string(void) const{
70
    std::string addr = "";
71
    BOOST_FOREACH(boost::uint8_t byte, this->to_bytes()){
72
        addr += str(boost::format("%s%02x") % ((addr == "")?"":":") % int(byte));
73
    }
74
    return addr;
75
}