本文介绍了Linux C ++如何以编程方式获取LAN上所有适配器的MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C或C ++ PROGRAM (无命令行)在我的(小型)本地计算机上获取MAC地址(如果IP地址为免费",我也将使用IP地址)网络.它是嵌入式的Busybox Linux,因此我需要一个简单的答案,希望它不需要移植某些库.我没有libnet或libpcap.如果是DHCP主机,则arp缓存似乎从不包含任何其他内容.

How may I use C or C++ PROGRAM (no command line) to get the MAC addresses (I'll take the IP addresses too if they are "free") on my (small) local network. It's an embedded Busybox Linux so I need a minimalist answer that hopefully doesn't require porting some library. I don't have libnet or libpcap. The arp cache seems to never contain anything but the MAC if the DHCP host.

推荐答案

此处的完整源代码.

打开/proc/net/arp,然后像这样读取每一行:

Open /proc/net/arp, then read each line like this:

char line[500]; // Read with fgets().
char ip_address[500]; // Obviously more space than necessary, just illustrating here.
int hw_type;
int flags;
char mac_address[500];
char mask[500];
char device[500];

FILE *fp = xfopen("/proc/net/arp", "r");
fgets(line, sizeof(line), fp);    // Skip the first line (column headers).
while(fgets(line, sizeof(line), fp))
{
    // Read the data.
    sscanf(line, "%s 0x%x 0x%x %s %s %s\n",
          ip_address,
          &hw_type,
          &flags,
          mac_address,
          mask,
          device);

    // Do stuff with it.
}

fclose(fp);

这是直接从BusyBox的arp实现中获得的,位于 BusyBox 1.21的busybox-1_21_0/networking/arp.c目录中.0压缩包.尤其要看arp_show()函数.

This was taken straight from BusyBox's implementation of arp, in busybox-1_21_0/networking/arp.c directory of the BusyBox 1.21.0 tarball. Look at the arp_show() function in particular.

如果您害怕C:

命令arp -a应该为您提供所需的MAC地址和IP地址.

The command arp -a should give you what you want, both MAC addresses and IP addresses.

要获取子网中的所有MAC地址,您可以尝试

To get all MAC addresses on a subnet, you can try

nmap -n -sP <subnet>
arp -a | grep -v incomplete

这篇关于Linux C ++如何以编程方式获取LAN上所有适配器的MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:25