blob: bbaaec350fd2aa749e182a1f81ba557632344b5e [file] [log] [blame]
Elliott Hughes9cddb482016-01-04 20:38:05 +00001/*
2 * Copyright (C) 2015 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 <gtest/gtest.h>
18
19#include <ifaddrs.h>
20
Yi Kongfdb29632015-12-22 17:07:23 +000021#include <linux/if_packet.h>
22#include <netinet/in.h>
23
Elliott Hughes9cddb482016-01-04 20:38:05 +000024TEST(ifaddrs, freeifaddrs_null) {
25 freeifaddrs(nullptr);
26}
27
28TEST(ifaddrs, getifaddrs_smoke) {
29 ifaddrs* addrs = nullptr;
30
31 ASSERT_EQ(0, getifaddrs(&addrs));
32 ASSERT_TRUE(addrs != nullptr);
33
Yi Kongfdb29632015-12-22 17:07:23 +000034 // We can't say much about what network interfaces are available, but we can be pretty
35 // sure there's a loopback interface, and that it has IPv4, IPv6, and AF_PACKET entries.
36 ifaddrs* lo_inet4 = nullptr;
37 ifaddrs* lo_inet6 = nullptr;
38 ifaddrs* lo_packet = nullptr;
Elliott Hughes9cddb482016-01-04 20:38:05 +000039 for (ifaddrs* addr = addrs; addr != nullptr; addr = addr->ifa_next) {
Yi Kongfdb29632015-12-22 17:07:23 +000040 if (addr->ifa_name && strcmp(addr->ifa_name, "lo") == 0) {
41 if (addr->ifa_addr && addr->ifa_addr->sa_family == AF_INET) lo_inet4 = addr;
42 else if (addr->ifa_addr && addr->ifa_addr->sa_family == AF_INET6) lo_inet6 = addr;
43 else if (addr->ifa_addr && addr->ifa_addr->sa_family == AF_PACKET) lo_packet = addr;
44 }
Elliott Hughes9cddb482016-01-04 20:38:05 +000045 }
Yi Kongfdb29632015-12-22 17:07:23 +000046
47 // Does the IPv4 entry look right?
48 ASSERT_TRUE(lo_inet4 != nullptr);
49 const sockaddr_in* sa_inet4 = reinterpret_cast<const sockaddr_in*>(lo_inet4->ifa_addr);
50 ASSERT_TRUE(ntohl(sa_inet4->sin_addr.s_addr) == INADDR_LOOPBACK);
51
52 // Does the IPv6 entry look right?
53 ASSERT_TRUE(lo_inet6 != nullptr);
54 const sockaddr_in6* sa_inet6 = reinterpret_cast<const sockaddr_in6*>(lo_inet6->ifa_addr);
55 ASSERT_TRUE(IN6_IS_ADDR_LOOPBACK(&sa_inet6->sin6_addr));
56
57 // Does the AF_PACKET entry look right?
58 ASSERT_TRUE(lo_packet != nullptr);
59 const sockaddr_ll* sa_ll = reinterpret_cast<const sockaddr_ll*>(lo_packet->ifa_addr);
60 ASSERT_EQ(6, sa_ll->sll_halen);
Elliott Hughes9cddb482016-01-04 20:38:05 +000061
62 freeifaddrs(addrs);
63}