0

netlink用来获取接口、它的名称、类型等,但我无法获取 L2 地址(ugly_datais nlmsghdr*):

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_始终为空。我做错了什么以及如何获取地址?

4

2 回答 2

4

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

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;

这对我有用。

于 2013-02-03T15:51:39.400 回答
0

这是一个 Python (Linux) 的“解决方案”(可能对某人有所帮助):
这是 Python Netlink 库中的第一个示例:
请参阅:https
://pypi.python.org/pypi/pyroute2/0.2.16 非常简单的安装:

$ sudo pip install pyroute2  

将其粘贴在一个文件中(我称之为 netlink1.py)并使其可执行:

#!/usr/bin/env python
from pyroute2 import IPRoute

# get access to the netlink socket
ip = IPRoute()

# print interfaces
print ip.get_links()

# stop working with netlink and release all sockets
# ip.release() (deprecated)
ip.close()

这会在一行上打印出来,然后:

$ ./netlink1.py | sed 's/\], /\n/g' | grep IFLA_ADD
于 2014-11-25T23:51:34.553 回答