OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 #include "chromeos/network/network_util.h" |
| 6 |
| 7 #include "base/string_tokenizer.h" |
| 8 #include "base/stringprintf.h" |
| 9 |
| 10 namespace chromeos { |
| 11 |
| 12 SMS::SMS() : validity(0), msgclass(0) { |
| 13 } |
| 14 |
| 15 SMS::~SMS() { |
| 16 } |
| 17 |
| 18 WifiAccessPoint::WifiAccessPoint() |
| 19 : signal_strength(0), |
| 20 signal_to_noise(0), |
| 21 channel(0) { |
| 22 } |
| 23 |
| 24 WifiAccessPoint::~WifiAccessPoint() { |
| 25 } |
| 26 |
| 27 namespace network_util { |
| 28 |
| 29 std::string PrefixLengthToNetmask(int32 prefix_length) { |
| 30 std::string netmask; |
| 31 // Return the empty string for invalid inputs. |
| 32 if (prefix_length < 0 || prefix_length > 32) |
| 33 return netmask; |
| 34 for (int i = 0; i < 4; i++) { |
| 35 int remainder = 8; |
| 36 if (prefix_length >= 8) { |
| 37 prefix_length -= 8; |
| 38 } else { |
| 39 remainder = prefix_length; |
| 40 prefix_length = 0; |
| 41 } |
| 42 if (i > 0) |
| 43 netmask += "."; |
| 44 int value = remainder == 0 ? 0 : |
| 45 ((2L << (remainder - 1)) - 1) << (8 - remainder); |
| 46 netmask += StringPrintf("%d", value); |
| 47 } |
| 48 return netmask; |
| 49 } |
| 50 |
| 51 int32 NetmaskToPrefixLength(const std::string& netmask) { |
| 52 int count = 0; |
| 53 int prefix_length = 0; |
| 54 StringTokenizer t(netmask, "."); |
| 55 while (t.GetNext()) { |
| 56 // If there are more than 4 numbers, then it's invalid. |
| 57 if (count == 4) |
| 58 return -1; |
| 59 |
| 60 std::string token = t.token(); |
| 61 // If we already found the last mask and the current one is not |
| 62 // "0" then the netmask is invalid. For example, 255.224.255.0 |
| 63 if (prefix_length / 8 != count) { |
| 64 if (token != "0") |
| 65 return -1; |
| 66 } else if (token == "255") { |
| 67 prefix_length += 8; |
| 68 } else if (token == "254") { |
| 69 prefix_length += 7; |
| 70 } else if (token == "252") { |
| 71 prefix_length += 6; |
| 72 } else if (token == "248") { |
| 73 prefix_length += 5; |
| 74 } else if (token == "240") { |
| 75 prefix_length += 4; |
| 76 } else if (token == "224") { |
| 77 prefix_length += 3; |
| 78 } else if (token == "192") { |
| 79 prefix_length += 2; |
| 80 } else if (token == "128") { |
| 81 prefix_length += 1; |
| 82 } else if (token == "0") { |
| 83 prefix_length += 0; |
| 84 } else { |
| 85 // mask is not a valid number. |
| 86 return -1; |
| 87 } |
| 88 count++; |
| 89 } |
| 90 if (count < 4) |
| 91 return -1; |
| 92 return prefix_length; |
| 93 } |
| 94 |
| 95 } // namespace network_util |
| 96 } // namespace chromeos |
OLD | NEW |