如何通过netlink获得网络链路L2地址
How to get network link L2 address via netlink?
我使用netlink
来获取接口,其名称,类型等,但我无法获得L2地址(ugly_data
是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_
总是空的。我做错了什么,如何获得地址?
可能问题是这里的硬件地址不是字符串。试着像这样获取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;
Python (Linux)'solution'(可能对某人有帮助):
这是来自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
相关文章:
- vscode g++链路故障:体系结构x86_64的未定义符号
- GLFW DDS 加载函数的 OpenGL 链路错误
- QBS 为静态链路 MSVC 创建静态库
- VS 链路错误描述中的"@@YAHXZ"是什么意思?
- 数据结构:多(A)对多(B)关系,每个链路也有自己的数据(C)
- 在 OpenGL 计划链路状态检查期间"No definition of main in vertex shader"
- 提升单元测试链路错误
- C++ shared_ptr基于单调导致链路错误的原因
- 为什么Typedef结构会产生链路故障
- 链路寄存器 (LR) 是否受内联函数或裸函数的影响
- 如何查找 IP 地址是否为链路本地地址
- C 程序检测物理链路状态和数据包丢失
- 如何处理系统链路控制的NM_CLICK
- MPG123 链路错误"_read"和"_lseek"
- 在VS2012中使用时出现log4cplus链路错误
- C、 所有平台中进程的C++CPU使用率和内存使用率+当前时间的可用网络下行链路带宽
- Parasoft c++测试链路单元测试错误
- 在ns3中的两个节点之间创建无线链路
- 设置链路顺序和LINK_INTERFACE_MULTIPLICITY
- 如何通过netlink获得网络链路L2地址