Maciej Żenczykowski | b70da76 | 2019-01-28 15:20:48 -0800 | [diff] [blame] | 1 | /* |
| 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 Żenczykowski | 0a7dce8 | 2019-01-28 15:31:55 -0800 | [diff] [blame^] | 19 | #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 Żenczykowski | b70da76 | 2019-01-28 15:20:48 -0800 | [diff] [blame] | 26 | #define LOG_TAG "ClatUtils" |
| 27 | #include <log/log.h> |
| 28 | |
Maciej Żenczykowski | 0a7dce8 | 2019-01-28 15:31:55 -0800 | [diff] [blame^] | 29 | #include "android-base/unique_fd.h" |
| 30 | |
Maciej Żenczykowski | b70da76 | 2019-01-28 15:20:48 -0800 | [diff] [blame] | 31 | namespace android { |
| 32 | namespace net { |
| 33 | |
Maciej Żenczykowski | 0a7dce8 | 2019-01-28 15:31:55 -0800 | [diff] [blame^] | 34 | int 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 Żenczykowski | b70da76 | 2019-01-28 15:20:48 -0800 | [diff] [blame] | 57 | } // namespace net |
| 58 | } // namespace android |