1 /******************************************************************************
2 *
3 * Copyright 2019 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 #include "hci/address.h"
20
21 #include <stdint.h>
22 #include <algorithm>
23 #include <sstream>
24 #include <vector>
25
26 #include "os/log.h"
27
28 namespace bluetooth {
29 namespace hci {
30
31 static_assert(sizeof(Address) == 6, "Address must be 6 bytes long!");
32
33 const Address Address::kAny{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
34 const Address Address::kEmpty{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
35
Address(const uint8_t (& addr)[6])36 Address::Address(const uint8_t (&addr)[6]) {
37 std::copy(addr, addr + kLength, address);
38 };
39
ToString() const40 std::string Address::ToString() const {
41 char buffer[] = "00:00:00:00:00:00";
42 std::snprintf(&buffer[0], sizeof(buffer), "%02x:%02x:%02x:%02x:%02x:%02x", address[5], address[4], address[3],
43 address[2], address[1], address[0]);
44 std::string str(buffer);
45 return str;
46 }
47
FromString(const std::string & from,Address & to)48 bool Address::FromString(const std::string& from, Address& to) {
49 Address new_addr;
50 if (from.length() != 17) {
51 return false;
52 }
53
54 std::istringstream stream(from);
55 std::string token;
56 int index = 0;
57 while (getline(stream, token, ':')) {
58 if (index >= 6) {
59 return false;
60 }
61
62 if (token.length() != 2) {
63 return false;
64 }
65
66 char* temp = nullptr;
67 new_addr.address[5 - index] = strtol(token.c_str(), &temp, 16);
68 if (*temp != '\0') {
69 return false;
70 }
71
72 index++;
73 }
74
75 if (index != 6) {
76 return false;
77 }
78
79 to = new_addr;
80 return true;
81 }
82
FromOctets(const uint8_t * from)83 size_t Address::FromOctets(const uint8_t* from) {
84 std::copy(from, from + kLength, address);
85 return kLength;
86 };
87
IsValidAddress(const std::string & address)88 bool Address::IsValidAddress(const std::string& address) {
89 Address tmp;
90 return Address::FromString(address, tmp);
91 }
92
93 } // namespace hci
94 } // namespace bluetooth
95