我参考网络上如下代码,想监控网卡up down
int fd, retval;
char buf[BUFLEN] = {0};
int len = BUFLEN;
struct sockaddr_nl addr;
struct nlmsghdr *nh;
struct ifinfomsg *ifinfo;
struct rtattr *attr;
fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_groups = RTNLGRP_LINK;
bind(fd, (struct sockaddr*)&addr, sizeof(addr));
while ((retval = read(fd, buf, BUFLEN)) > 0)
{
for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, retval); nh = NLMSG_NEXT(nh, retval))
{
if (nh->nlmsg_type == NLMSG_DONE)
break;
else if (nh->nlmsg_type == NLMSG_ERROR)
break;
else if (nh->nlmsg_type != RTM_NEWLINK)
continue;
ifinfo = NLMSG_DATA(nh);
printf("%u: %s", ifinfo->ifi_index,
(ifinfo->ifi_flags & IFF_RUNNING) ? "up" : "down" );
attr = (struct rtattr*)(((char*)nh) + NLMSG_SPACE(sizeof(*ifinfo)));
len = nh->nlmsg_len - NLMSG_SPACE(sizeof(*ifinfo));
for (; RTA_OK(attr, len); attr = RTA_NEXT(attr, len))
{
if (attr->rta_type == IFLA_IFNAME)
{
printf(" %s", (char*)RTA_DATA(attr));
break;
}
}
printf("\n");
}
}
return 0;
然后使用ifconfig up/down来控制网卡打开关闭
发现配置down,只打印一次down,正常
配置up,会打印2次up信息,这是为什么呢
--
FROM 140.224.74.*