host_port_pair.cc revision dc0f95d653279beabeb9817299e2902918ba123e
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 13namespace net { 14 15HostPortPair::HostPortPair() : port_(0) {} 16HostPortPair::HostPortPair(const std::string& in_host, uint16 in_port) 17 : host_(in_host), port_(in_port) {} 18 19// static 20HostPortPair HostPortPair::FromURL(const GURL& url) { 21 return HostPortPair(url.HostNoBrackets(), url.EffectiveIntPort()); 22} 23 24// static 25HostPortPair HostPortPair::FromAddrInfo(const struct addrinfo* ai) { 26 return HostPortPair(NetAddressToString(ai), 27 GetPortFromSockaddr(ai->ai_addr, ai->ai_addrlen)); 28} 29 30std::string HostPortPair::ToString() const { 31 return base::StringPrintf("%s:%u", HostForURL().c_str(), port_); 32} 33 34std::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