1 #include <errno.h> 2 #include <gtest/gtest.h> 3 #include <ifaddrs.h> 4 #include <net/if.h> 5 #include <string> 6 using namespace testing::ext; 7 8 class NetIfTest : public testing::Test { SetUp()9 void SetUp() override {} TearDown()10 void TearDown() override {} 11 }; 12 13 /** 14 * @tc.name: if_nametoindex_001 15 * @tc.desc: Validate the functionality of the if_nametoindex function in retrieving the index of a network interface 16 * based on its name 17 * @tc.type: FUNC 18 **/ 19 HWTEST_F(NetIfTest, if_nametoindex_001, TestSize.Level1) 20 { 21 struct ifaddrs* ifAddr; 22 ASSERT_NE(-1, getifaddrs(&ifAddr)); 23 unsigned index = if_nametoindex(ifAddr->ifa_name); 24 EXPECT_NE(index, 0U); 25 freeifaddrs(ifAddr); 26 } 27 28 /** 29 * @tc.name: if_indextoname_001 30 * @tc.desc: Validate the functionality of the if_indextoname function in retrieving the name of a network interface 31 * based on its index 32 * @tc.type: FUNC 33 **/ 34 HWTEST_F(NetIfTest, if_indextoname_001, TestSize.Level1) 35 { 36 struct ifaddrs* ifAddr; 37 ASSERT_NE(-1, getifaddrs(&ifAddr)); 38 unsigned index = if_nametoindex(ifAddr->ifa_name); 39 EXPECT_NE(index, 0U); 40 char s[IF_NAMESIZE] = {}; 41 memset(&s, 0, sizeof(s)); 42 char* name = if_indextoname(index, s); 43 EXPECT_STREQ(ifAddr->ifa_name, name); 44 freeifaddrs(ifAddr); 45 } 46 47 /** 48 * @tc.name: if_nameindex_001 49 * @tc.desc: Ensure that the if_nameindex function successfully retrieves a list of network interface names and indices 50 * @tc.type: FUNC 51 **/ 52 HWTEST_F(NetIfTest, if_nameindex_001, TestSize.Level1) 53 { 54 auto list = std::unique_ptr<struct if_nameindex, decltype(&if_freenameindex)>(if_nameindex(), &if_freenameindex); 55 ASSERT_NE(list, nullptr); 56 57 char buf[IF_NAMESIZE] = {}; 58 memset(&buf, 0, sizeof(buf)); 59 60 for (struct if_nameindex* it = list.get(); it->if_index != 0; ++it) { 61 fprintf(stderr, "\t%d\t%s\n", it->if_index, it->if_name); 62 unsigned int result1 = if_nametoindex(it->if_name); 63 char* result2 = if_indextoname(it->if_index, buf); 64 EXPECT_EQ(it->if_index, result1); 65 EXPECT_STREQ(it->if_name, result2); 66 } 67 }