c++ - 如何通过netlink获取网络链接L2地址?

标签 c++ linux netlink

我正在使用 netlink 获取接口(interface)、它的名称、类型等,但我无法获取 L2 地址(ugly_datanlmsghdr*):

struct ifinfomsg *iface;
struct rtattr *attribute;
int len;

iface = (struct ifinfomsg *) NLMSG_DATA(ugly_data);
len = ugly_data->nlmsg_len - NLMSG_LENGTH(sizeof(*iface));

for (attribute = IFLA_RTA(iface);
     RTA_OK(attribute, len);
     attribute = RTA_NEXT(attribute, len))
{
  id_ = iface->ifi_index;

  // get type
  switch (iface->ifi_type)
  {
  case ARPHRD_ETHER:
    type_ = "Ethernet";
    break;
  case ...
  }

  // get attributes
  switch (attribute->rta_type)
  {
  case IFLA_IFNAME:
    name_ = (char *) RTA_DATA(attribute);
    break;
  case IFLA_ADDRESS:
    address_ = (char *) RTA_DATA(attribute);
    break;
   ...
  }
}

type_id_name_ 包含正确的值,与我从 ifconfig 获得的相同,但是 address_ 始终为空。 我做错了什么以及如何获取地址?

最佳答案

可能问题是这里的硬件地址不是字符串。尝试像这样获取地址:

case IFLA_ADDRESS:
  char buffer[64];
  unsigned char* ptr = (unsigned char*)RTA_DATA(attribute);
  snprintf(buffer, 64, " %02x:%02x:%02x:%02x:%02x:%02x", 
      ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
  std::cout << "address : " << buffer << std::endl;

这对我有用。

关于c++ - 如何通过netlink获取网络链接L2地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368306/

相关文章:

c++ - 我能以某种方式将 Maple 过程包含到 C++ 代码中吗

c++ - 如何为使用Clang LLVM编译的C++代码生成图形代码配置文件报告?

c++ - 带有堆的 Bellman-Ford 不适用于自定义比较功能

linux - 如何在 bash 中同步处理 2 个范围/列表

c++ - 无法让 Ocean Optics OmniDriver 工作

基于每个域用户的 PHP 配置在 fastcgi apache 服务器运行时不起作用

c++ - 当使用 stdout 输出二进制数据时,如何将调试/详细信息输出到终端?

C++ NetLink 套接字错误

go - 什么字段对应于 netlink 中的 "dev"(设备)参数?

c - netlink_kernel_create 不适用于最新的 Linux 内核