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
#include <string.h>
8
#include <unistd.h>
9
#include <sys/ioctl.h>
10
#include <sys/socket.h>
11
#include <sys/types.h>
12
#include <net/if.h>
13
#include <netdb.h>
14
15
#include "mozilla/DebugOnly.h"
16
#include "mozilla/ScopeExit.h"
17
18
#include "NetworkInfoServiceImpl.h"
19
20
namespace mozilla {
21
namespace net {
22
23
static nsresult ListInterfaceAddresses(int aFd, const char* aIface,
24
AddrMapType& aAddrMap);
25
26
nsresult DoListAddresses(AddrMapType& aAddrMap) {
27
int fd = socket(AF_INET, SOCK_DGRAM, 0);
28
if (fd < 0) {
29
return NS_ERROR_FAILURE;
30
}
31
32
auto autoCloseSocket = MakeScopeExit([&] { close(fd); });
33
34
struct ifconf ifconf;
35
/* 16k of space should be enough to list all interfaces. Worst case, if it's
36
* not then we will error out and fail to list addresses. This should only
37
* happen on pathological machines with way too many interfaces.
38
*/
39
char buf[16384];
40
41
ifconf.ifc_len = sizeof(buf);
42
ifconf.ifc_buf = buf;
43
if (ioctl(fd, SIOCGIFCONF, &ifconf) != 0) {
44
return NS_ERROR_FAILURE;
45
}
46
47
struct ifreq* ifreq = ifconf.ifc_req;
48
int i = 0;
49
while (i < ifconf.ifc_len) {
50
size_t len = sizeof(struct ifreq);
51
52
DebugOnly<nsresult> rv =
53
ListInterfaceAddresses(fd, ifreq->ifr_name, aAddrMap);
54
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "ListInterfaceAddresses failed");
55
56
ifreq = (struct ifreq*)((char*)ifreq + len);
57
i += len;
58
}
59
60
return NS_OK;
61
}
62
63
static nsresult ListInterfaceAddresses(int aFd, const char* aInterface,
64
AddrMapType& aAddrMap) {
65
struct ifreq ifreq;
66
memset(&ifreq, 0, sizeof(struct ifreq));
67
strncpy(ifreq.ifr_name, aInterface, IFNAMSIZ - 1);
68
if (ioctl(aFd, SIOCGIFADDR, &ifreq) != 0) {
69
return NS_ERROR_FAILURE;
70
}
71
72
char host[128];
73
switch (ifreq.ifr_addr.sa_family) {
74
case AF_INET:
75
case AF_INET6:
76
getnameinfo(&ifreq.ifr_addr, sizeof(ifreq.ifr_addr), host, sizeof(host),
77
nullptr, 0, NI_NUMERICHOST);
78
break;
79
case AF_UNSPEC:
80
return NS_OK;
81
default:
82
// Unknown family.
83
return NS_OK;
84
}
85
86
nsCString ifaceStr;
87
ifaceStr.AssignASCII(aInterface);
88
89
nsCString addrStr;
90
addrStr.AssignASCII(host);
91
92
aAddrMap.Put(ifaceStr, addrStr);
93
94
return NS_OK;
95
}
96
97
} // namespace net
98
} // namespace mozilla