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/. */
10 #include <sys/socket.h>
11 #include <sys/types.h>
15 #include "mozilla/DebugOnly.h"
16 #include "mozilla/ScopeExit.h"
18 #include "NetworkInfoServiceImpl.h"
23 static nsresult
ListInterfaceAddresses(int aFd
, const char* aIface
,
24 AddrMapType
& aAddrMap
);
26 nsresult
DoListAddresses(AddrMapType
& aAddrMap
) {
27 int fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
29 return NS_ERROR_FAILURE
;
32 auto autoCloseSocket
= MakeScopeExit([&] { close(fd
); });
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.
41 ifconf
.ifc_len
= sizeof(buf
);
43 if (ioctl(fd
, SIOCGIFCONF
, &ifconf
) != 0) {
44 return NS_ERROR_FAILURE
;
47 struct ifreq
* ifreq
= ifconf
.ifc_req
;
49 while (i
< ifconf
.ifc_len
) {
50 size_t len
= IFNAMSIZ
+ ifreq
->ifr_addr
.sa_len
;
52 DebugOnly
<nsresult
> rv
=
53 ListInterfaceAddresses(fd
, ifreq
->ifr_name
, aAddrMap
);
54 NS_WARNING_ASSERTION(NS_SUCCEEDED(rv
), "ListInterfaceAddresses failed");
56 ifreq
= (struct ifreq
*)((char*)ifreq
+ len
);
60 autoCloseSocket
.release();
64 static nsresult
ListInterfaceAddresses(int aFd
, const char* aInterface
,
65 AddrMapType
& aAddrMap
) {
67 memset(&ifreq
, 0, sizeof(struct ifreq
));
68 strncpy(ifreq
.ifr_name
, aInterface
, IFNAMSIZ
- 1);
69 if (ioctl(aFd
, SIOCGIFADDR
, &ifreq
) != 0) {
70 return NS_ERROR_FAILURE
;
75 switch (family
= ifreq
.ifr_addr
.sa_family
) {
78 getnameinfo(&ifreq
.ifr_addr
, sizeof(ifreq
.ifr_addr
), host
, sizeof(host
),
79 nullptr, 0, NI_NUMERICHOST
);
89 ifaceStr
.AssignASCII(aInterface
);
92 addrStr
.AssignASCII(host
);
94 aAddrMap
.Put(ifaceStr
, addrStr
);
100 } // namespace mozilla