blob: 4ea0266b798f33fda44934f63e2562a6fe95d32e [file] [log] [blame]
lukasza0d40d8a2015-03-03 18:36:281// Copyright 2015 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 "remoting/protocol/port_range.h"
6
7#include <limits.h>
avi5a080f012015-12-22 23:15:438#include <stddef.h>
lukasza0d40d8a2015-03-03 18:36:289#include <stdlib.h>
10
11#include "base/strings/string_number_conversions.h"
12#include "base/strings/string_util.h"
13
14namespace remoting {
15
16bool PortRange::Parse(const std::string& port_range, PortRange* result) {
17 DCHECK(result);
18
19 if (port_range.empty()) {
20 result->min_port = 0;
21 result->max_port = 0;
22 return true;
23 }
24
25 size_t separator_index = port_range.find('-');
26 if (separator_index == std::string::npos)
27 return false;
28
29 std::string min_port_string, max_port_string;
30 base::TrimWhitespaceASCII(port_range.substr(0, separator_index),
31 base::TRIM_ALL, &min_port_string);
32 base::TrimWhitespaceASCII(port_range.substr(separator_index + 1),
33 base::TRIM_ALL, &max_port_string);
34
35 unsigned min_port, max_port;
36 if (!base::StringToUint(min_port_string, &min_port) ||
37 !base::StringToUint(max_port_string, &max_port)) {
38 return false;
39 }
40
41 if (min_port == 0 || min_port > max_port || max_port > USHRT_MAX)
42 return false;
43
avi5a080f012015-12-22 23:15:4344 result->min_port = static_cast<uint16_t>(min_port);
45 result->max_port = static_cast<uint16_t>(max_port);
lukasza0d40d8a2015-03-03 18:36:2846 return true;
47}
48
49std::ostream& operator<<(std::ostream& os, const PortRange& port_range) {
50 if (port_range.is_null()) {
51 os << "<no port range specified>";
52 } else {
53 os << "[" << port_range.min_port << ", " << port_range.max_port << "]";
54 }
55 return os;
56}
57
58} // namespace remoting