1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chromeos/network/network_util.h"
7 #include "base/strings/string_tokenizer.h"
8 #include "base/strings/stringprintf.h"
9 #include "third_party/cros_system_api/dbus/service_constants.h"
13 WifiAccessPoint::WifiAccessPoint()
19 WifiAccessPoint::~WifiAccessPoint() {
22 CellularScanResult::CellularScanResult() {
25 CellularScanResult::~CellularScanResult() {
28 namespace network_util {
30 std::string PrefixLengthToNetmask(int32 prefix_length) {
32 // Return the empty string for invalid inputs.
33 if (prefix_length < 0 || prefix_length > 32)
35 for (int i = 0; i < 4; i++) {
37 if (prefix_length >= 8) {
40 remainder = prefix_length;
45 int value = remainder == 0 ? 0 :
46 ((2L << (remainder - 1)) - 1) << (8 - remainder);
47 netmask += base::StringPrintf("%d", value);
52 int32 NetmaskToPrefixLength(const std::string& netmask) {
54 int prefix_length = 0;
55 base::StringTokenizer t(netmask, ".");
57 // If there are more than 4 numbers, then it's invalid.
61 std::string token = t.token();
62 // If we already found the last mask and the current one is not
63 // "0" then the netmask is invalid. For example, 255.224.255.0
64 if (prefix_length / 8 != count) {
67 } else if (token == "255") {
69 } else if (token == "254") {
71 } else if (token == "252") {
73 } else if (token == "248") {
75 } else if (token == "240") {
77 } else if (token == "224") {
79 } else if (token == "192") {
81 } else if (token == "128") {
83 } else if (token == "0") {
86 // mask is not a valid number.
96 bool ParseCellularScanResults(
97 const ListValue& list, std::vector<CellularScanResult>* scan_results) {
98 scan_results->clear();
99 scan_results->reserve(list.GetSize());
100 for (ListValue::const_iterator it = list.begin(); it != list.end(); ++it) {
101 if (!(*it)->IsType(base::Value::TYPE_DICTIONARY))
103 CellularScanResult scan_result;
104 const DictionaryValue* dict = static_cast<const DictionaryValue*>(*it);
105 // If the network id property is not present then this network cannot be
106 // connected to so don't include it in the results.
107 if (!dict->GetStringWithoutPathExpansion(shill::kNetworkIdProperty,
108 &scan_result.network_id))
110 dict->GetStringWithoutPathExpansion(shill::kStatusProperty,
111 &scan_result.status);
112 dict->GetStringWithoutPathExpansion(shill::kLongNameProperty,
113 &scan_result.long_name);
114 dict->GetStringWithoutPathExpansion(shill::kShortNameProperty,
115 &scan_result.short_name);
116 dict->GetStringWithoutPathExpansion(shill::kTechnologyProperty,
117 &scan_result.technology);
118 scan_results->push_back(scan_result);
123 } // namespace network_util
124 } // namespace chromeos