Home | History | Annotate | Download | only in rename_netiface
      1 /*
      2  * Copyright (C) 2018 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 "common/libs/net/netlink_client.h"
     18 #include "common/libs/net/network_interface.h"
     19 #include "common/libs/net/network_interface_manager.h"
     20 
     21 #include <net/if.h>
     22 #include <cstdio>
     23 
     24 // This command can only rename network interfaces that are *DOWN*
     25 
     26 int main(int argc, char *argv[]) {
     27   if (argc != 3) {
     28     fprintf(stderr, "usage: %s [ethA] [ethB]\n", argv[0]);
     29     return -1;
     30   }
     31   const char *const name = argv[1];
     32   int32_t index = if_nametoindex(name);
     33   if (index == 0) {
     34     fprintf(stderr, "%s: invalid interface name '%s'\n", argv[0], name);
     35     return -2;
     36   }
     37   const char *const new_name = argv[2];
     38   auto factory = cvd::NetlinkClientFactory::Default();
     39   std::unique_ptr<cvd::NetlinkClient> nl(factory->New(NETLINK_ROUTE));
     40   std::unique_ptr<cvd::NetworkInterfaceManager> nm(
     41       cvd::NetworkInterfaceManager::New(factory));
     42   std::unique_ptr<cvd::NetworkInterface> ni(nm->Open(new_name, name));
     43   bool res = false;
     44   if (ni) {
     45     ni->SetName(new_name);
     46     res = nm->ApplyChanges(*ni);
     47   }
     48   if (!res) {
     49     fprintf(stderr, "%s: renaming interface '%s' failed\n", argv[0], name);
     50     return -3;
     51   }
     52   return 0;
     53 }
     54