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.
5 #include "net/base/host_port_pair.h"
7 #include "base/logging.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "net/base/ip_endpoint.h"
13 #include "net/base/net_util.h"
18 HostPortPair::HostPortPair() : port_(0) {}
19 HostPortPair::HostPortPair(const std::string
& in_host
, uint16_t in_port
)
20 : host_(in_host
), port_(in_port
) {
24 HostPortPair
HostPortPair::FromURL(const GURL
& url
) {
25 return HostPortPair(url
.HostNoBrackets(),
26 static_cast<uint16_t>(url
.EffectiveIntPort()));
30 HostPortPair
HostPortPair::FromIPEndPoint(const IPEndPoint
& ipe
) {
31 return HostPortPair(ipe
.ToStringWithoutPort(), ipe
.port());
34 HostPortPair
HostPortPair::FromString(const std::string
& str
) {
35 std::vector
<std::string
> key_port
;
36 base::SplitString(str
, ':', &key_port
);
37 if (key_port
.size() != 2)
38 return HostPortPair();
40 if (!base::StringToInt(key_port
[1], &port
))
41 return HostPortPair();
42 if (!IsPortValid(port
))
43 return HostPortPair();
44 HostPortPair host_port_pair
;
45 host_port_pair
.set_host(key_port
[0]);
46 host_port_pair
.set_port(static_cast<uint16_t>(port
));
47 return host_port_pair
;
50 std::string
HostPortPair::ToString() const {
51 std::string
ret(HostForURL());
53 ret
+= base::IntToString(port_
);
57 std::string
HostPortPair::HostForURL() const {
58 // TODO(rtenneti): Add support for |host| to have '\0'.
59 if (host_
.find('\0') != std::string::npos
) {
60 std::string
host_for_log(host_
);
62 while ((nullpos
= host_for_log
.find('\0')) != std::string::npos
) {
63 host_for_log
.replace(nullpos
, 1, "%00");
65 LOG(DFATAL
) << "Host has a null char: " << host_for_log
;
67 // Check to see if the host is an IPv6 address. If so, added brackets.
68 if (host_
.find(':') != std::string::npos
) {
69 DCHECK_NE(host_
[0], '[');
70 return base::StringPrintf("[%s]", host_
.c_str());