3
* Copyright 2004--2005, Google Inc.
5
* Redistribution and use in source and binary forms, with or without
6
* modification, are permitted provided that the following conditions are met:
8
* 1. Redistributions of source code must retain the above copyright notice,
9
* this list of conditions and the following disclaimer.
10
* 2. Redistributions in binary form must reproduce the above copyright notice,
11
* this list of conditions and the following disclaimer in the documentation
12
* and/or other materials provided with the distribution.
13
* 3. The name of the author may not be used to endorse or promote products
14
* derived from this software without specific prior written permission.
16
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
#include "talk/base/socketaddress.h"
31
#include <sys/types.h>
32
#include <sys/socket.h>
33
#include <netinet/in.h>
35
#include <netinet/in_systm.h>
37
#include <netinet/ip.h>
38
#include <arpa/inet.h>
45
#include "talk/base/byteorder.h"
46
#include "talk/base/common.h"
47
#include "talk/base/logging.h"
48
#include "talk/base/nethelpers.h"
51
#include "talk/base/win32.h"
56
// Address family constants for STUN (see RFC 5389).
57
static const int kStunFamilyIPv4 = 1;
58
static const int kStunFamilyIPv6 = 2;
60
SocketAddress::SocketAddress() {
64
SocketAddress::SocketAddress(const std::string& hostname, int port) {
69
SocketAddress::SocketAddress(uint32 ip_as_host_order_integer, int port) {
70
SetIP(IPAddress(ip_as_host_order_integer));
74
SocketAddress::SocketAddress(const IPAddress& ip, int port) {
79
SocketAddress::SocketAddress(const SocketAddress& addr) {
80
this->operator=(addr);
83
void SocketAddress::Clear() {
86
ip_ = IPAddress(INADDR_ANY);
90
bool SocketAddress::IsNil() const {
91
return hostname_.empty() && IPIsAny(ip_) && 0 == port_;
94
bool SocketAddress::IsComplete() const {
95
return (!IPIsAny(ip_)) && (0 != port_);
98
SocketAddress& SocketAddress::operator=(const SocketAddress& addr) {
99
hostname_ = addr.hostname_;
102
literal_ = addr.literal_;
106
void SocketAddress::SetIP(uint32 ip_as_host_order_integer) {
109
ip_ = IPAddress(ip_as_host_order_integer);
112
void SocketAddress::SetIP(const IPAddress& ip) {
118
void SocketAddress::SetIP(const std::string& hostname) {
119
hostname_ = hostname;
120
literal_ = IPFromString(hostname, &ip_);
122
ip_ = IPAddress(INADDR_ANY);
126
void SocketAddress::SetResolvedIP(uint32 ip_as_host_order_integer) {
127
ip_ = IPAddress(ip_as_host_order_integer);
130
void SocketAddress::SetResolvedIP(const IPAddress& ip) {
134
void SocketAddress::SetPort(int port) {
135
ASSERT((0 <= port) && (port < 65536));
139
uint32 SocketAddress::ip() const {
140
return ip_.v4AddressAsHostOrderInteger();
143
const IPAddress& SocketAddress::ipaddr() const {
147
uint16 SocketAddress::port() const {
151
std::string SocketAddress::IPAsString() const {
152
// If the hostname was a literal IP string, it may need to have square
153
// brackets added (for SocketAddress::ToString()).
154
if (!literal_ && !hostname_.empty())
156
if (ip_.family() == AF_INET6) {
157
return "[" + ip_.ToString() + "]";
159
return ip_.ToString();
163
std::string SocketAddress::PortAsString() const {
164
std::ostringstream ost;
169
std::string SocketAddress::ToString() const {
170
std::ostringstream ost;
177
bool SocketAddress::FromString(const std::string& str) {
178
if (str.at(0) == '[') {
179
std::string::size_type closebracket = str.rfind(']');
180
if (closebracket != std::string::npos) {
181
std::string::size_type colon = str.find(':', closebracket);
182
if (colon != std::string::npos && colon > closebracket) {
183
SetPort(strtoul(str.substr(colon + 1).c_str(), NULL, 10));
184
SetIP(str.substr(1, closebracket - 1));
190
std::string::size_type pos = str.find(':');
191
if (std::string::npos == pos)
193
SetPort(strtoul(str.substr(pos + 1).c_str(), NULL, 10));
194
SetIP(str.substr(0, pos));
199
std::ostream& operator<<(std::ostream& os, const SocketAddress& addr) {
200
os << addr.IPAsString() << ":" << addr.port();
204
bool SocketAddress::IsAnyIP() const {
208
bool SocketAddress::IsLoopbackIP() const {
209
return IPIsLoopback(ip_) || (IPIsAny(ip_) &&
210
0 == strcmp(hostname_.c_str(), "localhost"));
213
bool SocketAddress::IsLocalIP() const {
217
std::vector<IPAddress> ips;
219
if (!hostname_.empty()
220
&& (0 == stricmp(hostname_.c_str(), GetHostname().c_str()))) {
223
} else if (GetLocalIPs(&ips)) {
224
for (size_t i = 0; i < ips.size(); ++i) {
233
bool SocketAddress::IsPrivateIP() const {
234
return IPIsPrivate(ip_);
237
bool SocketAddress::IsUnresolvedIP() const {
238
return IsAny() && !literal_ && !hostname_.empty();
241
bool SocketAddress::ResolveIP(bool force, int* error) {
242
if (hostname_.empty()) {
243
// nothing to resolve
244
} else if (!force && !IsAny()) {
247
LOG_F(LS_VERBOSE) << "(" << hostname_ << ")";
249
if (hostent* pHost = SafeGetHostByName(hostname_.c_str(), &errcode)) {
250
if (IPFromHostEnt(pHost, &ip_)) {
251
LOG_F(LS_VERBOSE) << "(" << hostname_ << ") resolved to: "
256
LOG_F(LS_ERROR) << "(" << hostname_ << ") err: " << errcode;
262
return (!IPIsAny(ip_));
265
bool SocketAddress::operator==(const SocketAddress& addr) const {
266
return EqualIPs(addr) && EqualPorts(addr);
269
bool SocketAddress::operator<(const SocketAddress& addr) const {
272
else if (addr.ip_ < ip_)
275
// We only check hostnames if both IPs are zero. This matches EqualIPs()
276
if (addr.IsAnyIP()) {
277
if (hostname_ < addr.hostname_)
279
else if (addr.hostname_ < hostname_)
283
return port_ < addr.port_;
286
bool SocketAddress::EqualIPs(const SocketAddress& addr) const {
287
return (ip_ == addr.ip_) &&
288
((!IPIsAny(ip_)) || (hostname_ == addr.hostname_));
291
bool SocketAddress::EqualPorts(const SocketAddress& addr) const {
292
return (port_ == addr.port_);
295
size_t SocketAddress::Hash() const {
298
h ^= port_ | (port_ << 16);
302
void SocketAddress::ToSockAddr(sockaddr_in* saddr) const {
303
memset(saddr, 0, sizeof(*saddr));
304
if (ip_.family() != AF_INET) {
305
saddr->sin_family = AF_UNSPEC;
308
saddr->sin_family = AF_INET;
309
saddr->sin_port = HostToNetwork16(port_);
311
saddr->sin_addr.s_addr = INADDR_ANY;
313
saddr->sin_addr = ip_.ipv4_address();
317
bool SocketAddress::FromSockAddr(const sockaddr_in& saddr) {
318
if (saddr.sin_family != AF_INET)
320
SetIP(NetworkToHost32(saddr.sin_addr.s_addr));
321
SetPort(NetworkToHost16(saddr.sin_port));
326
static size_t ToSockAddrStorageHelper(sockaddr_storage* addr,
327
IPAddress ip, int port, int scope_id) {
328
memset(addr, 0, sizeof(sockaddr_storage));
329
addr->ss_family = ip.family();
330
if (addr->ss_family == AF_INET6) {
331
sockaddr_in6* saddr = reinterpret_cast<sockaddr_in6*>(addr);
332
saddr->sin6_addr = ip.ipv6_address();
333
saddr->sin6_port = HostToNetwork16(port);
334
saddr->sin6_scope_id = scope_id;
335
return sizeof(sockaddr_in6);
336
} else if (addr->ss_family == AF_INET) {
337
sockaddr_in* saddr = reinterpret_cast<sockaddr_in*>(addr);
338
saddr->sin_addr = ip.ipv4_address();
339
saddr->sin_port = HostToNetwork16(port);
340
return sizeof(sockaddr_in);
345
size_t SocketAddress::ToDualStackSockAddrStorage(sockaddr_storage *addr) const {
346
return ToSockAddrStorageHelper(addr, ip_.AsIPv6Address(), port_, scope_id_);
349
size_t SocketAddress::ToSockAddrStorage(sockaddr_storage* addr) const {
350
return ToSockAddrStorageHelper(addr, ip_, port_, scope_id_);
353
std::string SocketAddress::IPToString(uint32 ip_as_host_order_integer) {
354
std::ostringstream ost;
355
ost << ((ip_as_host_order_integer >> 24) & 0xff);
357
ost << ((ip_as_host_order_integer >> 16) & 0xff);
359
ost << ((ip_as_host_order_integer >> 8) & 0xff);
361
ost << ((ip_as_host_order_integer >> 0) & 0xff);
365
bool SocketAddress::StringToIP(const std::string& hostname, uint32* ip) {
367
if (talk_base::inet_pton(AF_INET, hostname.c_str(), &addr) == 0)
369
*ip = NetworkToHost32(addr.s_addr);
373
bool SocketAddress::StringToIP(const std::string& hostname, IPAddress* ip) {
375
if (talk_base::inet_pton(AF_INET, hostname.c_str(), &addr4) > 0) {
377
*ip = IPAddress(addr4);
383
if (talk_base::inet_pton(AF_INET6, hostname.c_str(), &addr6) > 0) {
385
*ip = IPAddress(addr6);
392
uint32 SocketAddress::StringToIP(const std::string& hostname) {
394
StringToIP(hostname, &ip);
398
std::string SocketAddress::GetHostname() {
400
if (gethostname(hostname, ARRAY_SIZE(hostname)) == 0)
405
bool SocketAddress::GetLocalIPs(std::vector<IPAddress>* ips) {
411
const std::string hostname = SocketAddress::GetHostname();
412
if (hostname.empty())
416
if (hostent* pHost = SafeGetHostByName(hostname.c_str(), &errcode)) {
417
for (int i = 0; pHost->h_addr_list[i]; ++i) {
419
if (IPFromHostEnt(pHost, i, &ip)) {
424
return !ips->empty();
426
LOG(LS_ERROR) << "gethostbyname err: " << errcode;
430
bool SocketAddressFromSockAddrStorage(const sockaddr_storage& addr,
431
SocketAddress* out) {
435
if (addr.ss_family == AF_INET) {
436
const sockaddr_in* saddr = reinterpret_cast<const sockaddr_in*>(&addr);
437
*out = SocketAddress(IPAddress(saddr->sin_addr),
438
NetworkToHost16(saddr->sin_port));
440
} else if (addr.ss_family == AF_INET6) {
441
const sockaddr_in6* saddr = reinterpret_cast<const sockaddr_in6*>(&addr);
442
*out = SocketAddress(IPAddress(saddr->sin6_addr),
443
NetworkToHost16(saddr->sin6_port));
444
out->SetScopeID(saddr->sin6_scope_id);
449
} // namespace talk_base