• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <net/if.h>
18 
19 #include <errno.h>
20 #include <ifaddrs.h>
21 
22 #include <gtest/gtest.h>
23 
TEST(net_if,if_nametoindex_if_indextoname)24 TEST(net_if, if_nametoindex_if_indextoname) {
25   unsigned index;
26   index = if_nametoindex("lo");
27   ASSERT_NE(index, 0U);
28 
29   char buf[IF_NAMESIZE] = {};
30   char* name = if_indextoname(index, buf);
31   ASSERT_STREQ("lo", name);
32 }
33 
TEST(net_if,if_nametoindex_fail)34 TEST(net_if, if_nametoindex_fail) {
35   unsigned index = if_nametoindex("this-interface-does-not-exist");
36   ASSERT_EQ(0U, index);
37 }
38 
TEST(net_if,if_nameindex)39 TEST(net_if, if_nameindex) {
40   struct if_nameindex* list = if_nameindex();
41   ASSERT_TRUE(list != nullptr);
42 
43   ASSERT_TRUE(list->if_index != 0);
44 
45   std::set<std::string> if_nameindex_names;
46   char buf[IF_NAMESIZE] = {};
47   bool saw_lo = false;
48   for (struct if_nameindex* it = list; it->if_index != 0; ++it) {
49     fprintf(stderr, "\t%d\t%s\n", it->if_index, it->if_name);
50     if_nameindex_names.insert(it->if_name);
51     EXPECT_EQ(it->if_index, if_nametoindex(it->if_name));
52     EXPECT_STREQ(it->if_name, if_indextoname(it->if_index, buf));
53     if (strcmp(it->if_name, "lo") == 0) saw_lo = true;
54   }
55   ASSERT_TRUE(saw_lo);
56   if_freenameindex(list);
57 
58   std::set<std::string> getifaddrs_names;
59   ifaddrs* ifa;
60   ASSERT_EQ(0, getifaddrs(&ifa));
61   for (ifaddrs* it = ifa; it != nullptr; it = it->ifa_next) {
62     getifaddrs_names.insert(it->ifa_name);
63   }
64   freeifaddrs(ifa);
65 
66   ASSERT_EQ(getifaddrs_names, if_nameindex_names);
67 }
68 
TEST(net_if,if_freenameindex_nullptr)69 TEST(net_if, if_freenameindex_nullptr) {
70 #if defined(__BIONIC__)
71   if_freenameindex(nullptr);
72 #endif
73 }
74