94985948298bb16f2609f6638101ff1694e79b8e
[platform/upstream/connectedhomeip.git] / src / inet / tests / TapAddrAutoconf.cpp
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *    Copyright (c) 2019 Google LLC.
5  *    All rights reserved.
6  *
7  *    Licensed under the Apache License, Version 2.0 (the "License");
8  *    you may not use this file except in compliance with the License.
9  *    You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *    Unless required by applicable law or agreed to in writing, software
14  *    distributed under the License is distributed on an "AS IS" BASIS,
15  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *    See the License for the specific language governing permissions and
17  *    limitations under the License.
18  */
19
20 #include "TapAddrAutoconf.h"
21
22 #include <ifaddrs.h>
23 #include <inttypes.h>
24 #include <signal.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <sys/socket.h>
34 #include <sys/types.h>
35
36 int CollectTapAddresses(std::vector<char *> & addresses, const char * ifName)
37 {
38 #if CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS
39     struct ifaddrs *addrsList, *curAddr;
40     const int err = getifaddrs(&addrsList);
41
42     if (err == 0)
43     {
44         curAddr = addrsList;
45
46         while (curAddr)
47         {
48             if (strcmp(ifName, curAddr->ifa_name) == 0)
49             {
50                 char buf[INET6_ADDRSTRLEN];
51                 const char * rv;
52                 char * tmp;
53                 rv = inet_ntop(curAddr->ifa_addr->sa_family,
54                                curAddr->ifa_addr->sa_family == AF_INET6
55                                    ? (const void *) &(((sockaddr_in6 *) curAddr->ifa_addr)->sin6_addr)
56                                    : (const void *) &(((sockaddr_in *) curAddr->ifa_addr)->sin_addr),
57                                buf, sizeof(buf));
58                 if (rv != NULL)
59                 {
60                     tmp = (char *) malloc(strlen(buf));
61                     strcpy(tmp, buf);
62                     addresses.push_back(tmp);
63                 }
64             }
65             curAddr = curAddr->ifa_next;
66         }
67         freeifaddrs(addrsList);
68     }
69     else
70     {
71         return -1;
72     }
73
74     return 0;
75 #else
76 #error "Unsupported configuration: requires CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS"
77 #endif
78 }