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 "net/base/ip_endpoint.h"
12 #include "url/gurl.h"
13
14 namespace net {
15
HostPortPair()16 HostPortPair::HostPortPair() : port_(0) {}
HostPortPair(const std::string & in_host,uint16 in_port)17 HostPortPair::HostPortPair(const std::string& in_host, uint16 in_port)
18 : host_(in_host), port_(in_port) {}
19
20 // static
FromURL(const GURL & url)21 HostPortPair HostPortPair::FromURL(const GURL& url) {
22 return HostPortPair(url.HostNoBrackets(), url.EffectiveIntPort());
23 }
24
25 // static
FromIPEndPoint(const IPEndPoint & ipe)26 HostPortPair HostPortPair::FromIPEndPoint(const IPEndPoint& ipe) {
27 return HostPortPair(ipe.ToStringWithoutPort(), ipe.port());
28 }
29
FromString(const std::string & str)30 HostPortPair 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
ToString() const45 std::string HostPortPair::ToString() const {
46 return base::StringPrintf("%s:%u", HostForURL().c_str(), port_);
47 }
48
HostForURL() const49 std::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