1 /****************************************************************************** 2 * 3 * Copyright 2017 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 "raw_address.h" 20 21 #include <base/strings/string_split.h> 22 #include <base/strings/stringprintf.h> 23 #include <stdint.h> 24 #include <algorithm> 25 #include <vector> 26 27 static_assert(sizeof(RawAddress) == 6, "RawAddress must be 6 bytes long!"); 28 29 const RawAddress RawAddress::kAny{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}; 30 const RawAddress RawAddress::kEmpty{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; 31 32 RawAddress::RawAddress(const uint8_t (&addr)[6]) { 33 std::copy(addr, addr + kLength, address); 34 }; 35 36 std::string RawAddress::ToString() const { 37 return base::StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", address[0], 38 address[1], address[2], address[3], address[4], 39 address[5]); 40 } 41 42 bool RawAddress::FromString(const std::string& from, RawAddress& to) { 43 RawAddress new_addr; 44 if (from.length() != 17) return false; 45 46 std::vector<std::string> byte_tokens = 47 base::SplitString(from, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); 48 49 if (byte_tokens.size() != 6) return false; 50 51 for (int i = 0; i < 6; i++) { 52 const auto& token = byte_tokens[i]; 53 54 if (token.length() != 2) return false; 55 56 char* temp = nullptr; 57 new_addr.address[i] = strtol(token.c_str(), &temp, 16); 58 if (*temp != '\0') return false; 59 } 60 61 to = new_addr; 62 return true; 63 } 64 65 size_t RawAddress::FromOctets(const uint8_t* from) { 66 std::copy(from, from + kLength, address); 67 return kLength; 68 }; 69 70 bool RawAddress::IsValidAddress(const std::string& address) { 71 RawAddress tmp; 72 return RawAddress::FromString(address, tmp); 73 } 74