Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#if defined(XP_MACOSX) || defined(XP_LINUX)
8
# include <unistd.h>
9
#elif defined(XP_WIN)
10
# include <winsock2.h>
11
#endif
12
13
#include "nsNetworkInfoService.h"
14
#include "mozilla/ScopeExit.h"
15
16
#if defined(XP_MACOSX) || defined(XP_WIN) || defined(XP_LINUX)
17
# include "NetworkInfoServiceImpl.h"
18
#else
19
# error "Unsupported platform for nsNetworkInfoService! Check moz.build"
20
#endif
21
22
namespace mozilla {
23
namespace net {
24
25
NS_IMPL_ISUPPORTS(nsNetworkInfoService, nsINetworkInfoService)
26
27
nsNetworkInfoService::nsNetworkInfoService() = default;
28
29
nsresult nsNetworkInfoService::Init() { return NS_OK; }
30
31
nsresult nsNetworkInfoService::ListNetworkAddresses(
32
nsIListNetworkAddressesListener* aListener) {
33
nsresult rv;
34
35
AddrMapType addrMap;
36
rv = DoListAddresses(addrMap);
37
if (NS_WARN_IF(NS_FAILED(rv))) {
38
aListener->OnListNetworkAddressesFailed();
39
return NS_OK;
40
}
41
42
uint32_t addrCount = addrMap.Count();
43
nsTArray<nsCString> addrStrings;
44
if (!addrStrings.SetCapacity(addrCount, fallible)) {
45
aListener->OnListNetworkAddressesFailed();
46
return NS_OK;
47
}
48
49
for (auto iter = addrMap.Iter(); !iter.Done(); iter.Next()) {
50
addrStrings.AppendElement(iter.Data());
51
}
52
aListener->OnListedNetworkAddresses(addrStrings);
53
return NS_OK;
54
}
55
57
// Use platform-specific implementation of DoGetHostname on Cocoa and Windows.
58
static nsresult DoGetHostname(nsACString& aHostname) {
59
char hostnameBuf[256];
60
int result = gethostname(hostnameBuf, 256);
61
if (result == -1) {
62
return NS_ERROR_FAILURE;
63
}
64
65
// Ensure that there is always a terminating NUL byte.
66
hostnameBuf[255] = '\0';
67
68
// Find the first '.', terminate string there.
69
char* dotLocation = strchr(hostnameBuf, '.');
70
if (dotLocation) {
71
*dotLocation = '\0';
72
}
73
74
if (strlen(hostnameBuf) == 0) {
75
return NS_ERROR_FAILURE;
76
}
77
78
aHostname.AssignASCII(hostnameBuf);
79
return NS_OK;
80
}
81
82
nsresult nsNetworkInfoService::GetHostname(nsIGetHostnameListener* aListener) {
83
nsresult rv;
84
nsCString hostnameStr;
85
rv = DoGetHostname(hostnameStr);
86
if (NS_FAILED(rv)) {
87
aListener->OnGetHostnameFailed();
88
return NS_OK;
89
}
90
91
aListener->OnGotHostname(hostnameStr);
92
93
return NS_OK;
94
}
95
96
} // namespace net
97
} // namespace mozilla