blob: 6edc97a2a3644b78781b0eabbc76783ec3fc418d [file] [log] [blame]
Maciej Żenczykowskib70da762019-01-28 15:20:48 -08001/*
2 * Copyright (C) 2019 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 "ClatUtils.h"
18
Maciej Żenczykowski0a7dce82019-01-28 15:31:55 -080019#include <errno.h>
20#include <linux/if.h>
21#include <sys/ioctl.h>
22#include <sys/socket.h>
23#include <sys/types.h>
24#include <unistd.h>
25
Maciej Żenczykowskib70da762019-01-28 15:20:48 -080026#define LOG_TAG "ClatUtils"
27#include <log/log.h>
28
Maciej Żenczykowski0a7dce82019-01-28 15:31:55 -080029#include "android-base/unique_fd.h"
30
Maciej Żenczykowskib70da762019-01-28 15:20:48 -080031namespace android {
32namespace net {
33
Maciej Żenczykowski0a7dce82019-01-28 15:31:55 -080034int hardwareAddressType(const std::string& interface) {
35 base::unique_fd ufd(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
36
37 if (ufd < 0) {
38 const int err = errno;
39 ALOGE("socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0)");
40 return -err;
41 };
42
43 struct ifreq ifr = {};
44 // We use strncpy() instead of strlcpy() since kernel has to be able
45 // to handle non-zero terminated junk passed in by userspace anyway,
46 // and this way too long interface names (more than IFNAMSIZ-1 = 15
47 // characters plus terminating NULL) will not get truncated to 15
48 // characters and zero-terminated and thus potentially erroneously
49 // match a truncated interface if one were to exist.
50 strncpy(ifr.ifr_name, interface.c_str(), sizeof(ifr.ifr_name));
51
52 if (ioctl(ufd, SIOCGIFHWADDR, &ifr, sizeof(ifr))) return -errno;
53
54 return ifr.ifr_hwaddr.sa_family;
55}
56
Maciej Żenczykowskib70da762019-01-28 15:20:48 -080057} // namespace net
58} // namespace android