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> |
| 19 | |
| 20 | #include <net/if.h> |
| 21 | |
| 22 | #include "dirent.h" |
| 23 | #include "netdutils/Status.h" |
| 24 | #include "netdutils/Utils.h" |
| 25 | |
| 26 | namespace android { |
| 27 | namespace netdutils { |
| 28 | |
| 29 | StatusOr<std::vector<std::string>> getIfaceNames() { |
| 30 | std::vector<std::string> ifaceNames; |
| 31 | DIR* d; |
| 32 | struct dirent* de; |
| 33 | |
| 34 | if (!(d = opendir("/sys/class/net"))) { |
| 35 | return statusFromErrno(errno, "Cannot open iface directory"); |
| 36 | } |
| 37 | while ((de = readdir(d))) { |
| 38 | if ((de->d_type != DT_DIR) && (de->d_type != DT_LNK)) continue; |
| 39 | if (de->d_name[0] == '.') continue; |
| 40 | ifaceNames.push_back(std::string(de->d_name)); |
| 41 | } |
| 42 | closedir(d); |
| 43 | return ifaceNames; |
| 44 | } |
| 45 | |
| 46 | StatusOr<std::map<std::string, uint32_t>> getIfaceList() { |
| 47 | std::map<std::string, uint32_t> ifacePairs; |
| 48 | |
| 49 | ASSIGN_OR_RETURN(auto ifaceNames, getIfaceNames()); |
| 50 | |
| 51 | for (const auto& name : ifaceNames) { |
| 52 | uint32_t ifaceIndex = if_nametoindex(name.c_str()); |
| 53 | if (ifaceIndex) { |
| 54 | ifacePairs.insert(std::pair<std::string, uint32_t>(name, ifaceIndex)); |
| 55 | } |
| 56 | } |
| 57 | return ifacePairs; |
| 58 | } |
| 59 | |
| 60 | } // namespace netdutils |
| 61 | } // namespace android |