Linux C++ How to Programatically Get MAC address for all adapters on a LAN

爱⌒轻易说出口 提交于 2019-12-12 10:55:31

问题


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.


回答1:


Full source here.

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);

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.

If you're scared of C:

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

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

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


来源:https://stackoverflow.com/questions/21031755/linux-c-how-to-programatically-get-mac-address-for-all-adapters-on-a-lan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!