host_port_pair.cc revision 5e3f23d412006dc4db4e659864679f29341e113f
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 "net/base/host_port_pair.h"
6
7#include "base/strings/string_number_conversions.h"
8#include "base/strings/string_split.h"
9#include "base/strings/string_util.h"
10#include "base/strings/stringprintf.h"
11#include "googleurl/src/gurl.h"
12#include "net/base/ip_endpoint.h"
13
14namespace net {
15
16HostPortPair::HostPortPair() : port_(0) {}
17HostPortPair::HostPortPair(const std::string& in_host, uint16 in_port)
18    : host_(in_host), port_(in_port) {}
19
20// static
21HostPortPair HostPortPair::FromURL(const GURL& url) {
22  return HostPortPair(url.HostNoBrackets(), url.EffectiveIntPort());
23}
24
25// static
26HostPortPair HostPortPair::FromIPEndPoint(const IPEndPoint& ipe) {
27  return HostPortPair(ipe.ToStringWithoutPort(), ipe.port());
28}
29
30HostPortPair HostPortPair::FromString(const std::string& str) {
31  std::vector<std::string> key_port;
32  base::SplitString(str, ':', &key_port);
33  if (key_port.size() != 2)
34    return HostPortPair();
35  int port;
36  if (!base::StringToInt(key_port[1], &port))
37    return HostPortPair();
38  DCHECK_LT(port, 1 << 16);
39  HostPortPair host_port_pair;
40  host_port_pair.set_host(key_port[0]);
41  host_port_pair.set_port(port);
42  return host_port_pair;
43}
44
45std::string HostPortPair::ToString() const {
46  return base::StringPrintf("%s:%u", HostForURL().c_str(), port_);
47}
48
49std::string HostPortPair::HostForURL() const {
50  // Check to see if the host is an IPv6 address.  If so, added brackets.
51  if (host_.find(':') != std::string::npos) {
52    DCHECK_NE(host_[0], '[');
53    return base::StringPrintf("[%s]", host_.c_str());
54  }
55
56  return host_;
57}
58
59}  // namespace net
60