2013-01-16 67 views
0

我使用netlink得到的接口,它的名稱,型號等,但我不能得到L2地址(ugly_datanlmsghdr*):如何通過netlink獲取網絡鏈接L2地址?

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_總是空的。 我在做什麼錯誤以及如何獲取地址?

回答

1

也許斑點是這裏的硬件地址不是字符串。嘗試獲取像這樣的地址:

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; 

這對我有用。

0

下面是一個Python(Linux)的 '解決方案'(可以幫助別人):
這是在Python網絡鏈路庫中的第一個例子:
見: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