blob: 7b6d2c20cb0f674fc31c18d035e234746df525a9 [file] [log] [blame]
Elliott Hughes588213a2016-01-11 13:18:20 -08001/*
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>
Elliott Hughesed57b982016-01-15 21:02:56 -080020#include <ifaddrs.h>
Elliott Hughes588213a2016-01-11 13:18:20 -080021
22#include <gtest/gtest.h>
23
24TEST(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
34TEST(net_if, if_nametoindex_fail) {
Elliott Hughescc78f872025-08-06 14:19:41 -070035 unsigned index = if_nametoindex("does-not-exist");
Elliott Hughes588213a2016-01-11 13:18:20 -080036 ASSERT_EQ(0U, index);
37}
Elliott Hughesed57b982016-01-15 21:02:56 -080038
Elliott Hughescc78f872025-08-06 14:19:41 -070039TEST(net_if, if_nametoindex_too_long) {
40 // We have 16 bytes, but one of them needs to be the '\0'.
41 EXPECT_EQ(16, IFNAMSIZ);
42 const char* name = "01234567890123456";
43 unsigned index = if_nametoindex(name);
44 EXPECT_EQ(0U, index);
45 EXPECT_EQ(ENODEV, errno);
46}
47
Elliott Hughesed57b982016-01-15 21:02:56 -080048TEST(net_if, if_nameindex) {
49 struct if_nameindex* list = if_nameindex();
50 ASSERT_TRUE(list != nullptr);
51
52 ASSERT_TRUE(list->if_index != 0);
53
54 std::set<std::string> if_nameindex_names;
55 char buf[IF_NAMESIZE] = {};
56 bool saw_lo = false;
57 for (struct if_nameindex* it = list; it->if_index != 0; ++it) {
58 fprintf(stderr, "\t%d\t%s\n", it->if_index, it->if_name);
59 if_nameindex_names.insert(it->if_name);
60 EXPECT_EQ(it->if_index, if_nametoindex(it->if_name));
61 EXPECT_STREQ(it->if_name, if_indextoname(it->if_index, buf));
62 if (strcmp(it->if_name, "lo") == 0) saw_lo = true;
63 }
64 ASSERT_TRUE(saw_lo);
65 if_freenameindex(list);
66
67 std::set<std::string> getifaddrs_names;
68 ifaddrs* ifa;
69 ASSERT_EQ(0, getifaddrs(&ifa));
70 for (ifaddrs* it = ifa; it != nullptr; it = it->ifa_next) {
71 getifaddrs_names.insert(it->ifa_name);
72 }
73 freeifaddrs(ifa);
74
75 ASSERT_EQ(getifaddrs_names, if_nameindex_names);
76}
77
78TEST(net_if, if_freenameindex_nullptr) {
79#if defined(__BIONIC__)
80 if_freenameindex(nullptr);
81#endif
82}