1 // Copyright (c) 2010 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/string_util.h"
8 #include "base/stringprintf.h"
9 #include "googleurl/src/gurl.h"
10 #include "net/base/net_util.h"
11 #include "net/base/sys_addrinfo.h"
12
13 namespace net {
14
HostPortPair()15 HostPortPair::HostPortPair() : port_(0) {}
HostPortPair(const std::string & in_host,uint16 in_port)16 HostPortPair::HostPortPair(const std::string& in_host, uint16 in_port)
17 : host_(in_host), port_(in_port) {}
18
19 // static
FromURL(const GURL & url)20 HostPortPair HostPortPair::FromURL(const GURL& url) {
21 return HostPortPair(url.HostNoBrackets(), url.EffectiveIntPort());
22 }
23
24 // static
FromAddrInfo(const struct addrinfo * ai)25 HostPortPair HostPortPair::FromAddrInfo(const struct addrinfo* ai) {
26 return HostPortPair(NetAddressToString(ai),
27 GetPortFromSockaddr(ai->ai_addr, ai->ai_addrlen));
28 }
29
ToString() const30 std::string HostPortPair::ToString() const {
31 return base::StringPrintf("%s:%u", HostForURL().c_str(), port_);
32 }
33
HostForURL() const34 std::string HostPortPair::HostForURL() const {
35 // Check to see if the host is an IPv6 address. If so, added brackets.
36 if (host_.find(':') != std::string::npos) {
37 DCHECK_NE(host_[0], '[');
38 return base::StringPrintf("[%s]", host_.c_str());
39 }
40
41 return host_;
42 }
43
44 } // namespace net
45