waynema | 51800da | 2021-12-08 11:36:02 +0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2021 The Android Open Source Project |
| 3 | * |
| 4 | * |
| 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | * you may not use this file except in compliance with the License. |
| 7 | * You may obtain a copy of the License at |
| 8 | * |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | #include <map> |
Henri Chataing | 6cc0283 | 2023-11-03 23:26:47 +0000 | [diff] [blame^] | 19 | #include <vector> |
waynema | 51800da | 2021-12-08 11:36:02 +0800 | [diff] [blame] | 20 | |
| 21 | #include <net/if.h> |
| 22 | |
| 23 | #include "dirent.h" |
| 24 | #include "netdutils/Status.h" |
| 25 | #include "netdutils/Utils.h" |
| 26 | |
| 27 | namespace android { |
| 28 | namespace netdutils { |
| 29 | |
| 30 | StatusOr<std::vector<std::string>> getIfaceNames() { |
| 31 | std::vector<std::string> ifaceNames; |
| 32 | DIR* d; |
| 33 | struct dirent* de; |
| 34 | |
| 35 | if (!(d = opendir("/sys/class/net"))) { |
| 36 | return statusFromErrno(errno, "Cannot open iface directory"); |
| 37 | } |
| 38 | while ((de = readdir(d))) { |
| 39 | if ((de->d_type != DT_DIR) && (de->d_type != DT_LNK)) continue; |
| 40 | if (de->d_name[0] == '.') continue; |
| 41 | ifaceNames.push_back(std::string(de->d_name)); |
| 42 | } |
| 43 | closedir(d); |
| 44 | return ifaceNames; |
| 45 | } |
| 46 | |
| 47 | StatusOr<std::map<std::string, uint32_t>> getIfaceList() { |
| 48 | std::map<std::string, uint32_t> ifacePairs; |
| 49 | |
| 50 | ASSIGN_OR_RETURN(auto ifaceNames, getIfaceNames()); |
| 51 | |
| 52 | for (const auto& name : ifaceNames) { |
| 53 | uint32_t ifaceIndex = if_nametoindex(name.c_str()); |
| 54 | if (ifaceIndex) { |
| 55 | ifacePairs.insert(std::pair<std::string, uint32_t>(name, ifaceIndex)); |
| 56 | } |
| 57 | } |
| 58 | return ifacePairs; |
| 59 | } |
| 60 | |
| 61 | } // namespace netdutils |
| 62 | } // namespace android |