Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 259
Wes Miller Avatar asked Jan 09 '14 21:01

Wes Miller


People also ask

How do I find the MAC address of all devices on my network?

Enter ipconfig /all into the Command Prompt window and press Enter on your keyboard. The wireless MAC address will be listed under Wireless LAN adapter Wi-Fi next to Physical Address. The wired MAC address will be listed under Ethernet adapter Ethernet next to Physical Address.

How do I find my LAN MAC address Linux?

On a Linux machine Open a terminal window. Type ifconfig at the command prompt. Your MAC address will be displayed beside the label HWaddr.

How do I find the MAC address of another computer on another LAN?

You can use the arp command on any operating system to find the MAC address of another computer on your network. If you're using Windows, type cmd into the Windows Search bar, right-click Command prompt, and then select Run as administrator. On macOS, type Terminal into Spotlight search, and then double-click Terminal.


1 Answers

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
like image 157
Keeler Avatar answered Nov 02 '22 11:11

Keeler