Resolving MAC address for IP address using C++ on Linux

kagali-san picture kagali-san · Dec 19, 2010 · Viewed 19.6k times · Source

I need to generate an Ethernet header that includes the destination MAC address, (since libnfnetlink gives only the IP header before prerouting takes place), the outgoing interface number is also known, so the lookup can be made in the correct network.

What's the library/function to resolve the MAC address from an IP address?

Answer

Mr.Ree picture Mr.Ree · Dec 19, 2010

It's unclear why you need the MAC address, since that's usually handled for you at a lower level.

However, assuming your target is on your local Ethernet segment, you can use the arp command to look up values in the local cache. If the value is not cached... Well, that's a problem. Perhaps arping would help...

(Normally you'd send a packet to, for example, IP address 10.10.10.10, and your system would send an ARP packet out querying who-has 10.10.10.10, and a response would come back from that target system with its MAC address, and then it would be cached. (You can watch this happening with tcpdump.) Or when a system comes on line it would send out a broadcast message informing everyone else of its MAC address. Naturally, if your destination is on another Ethernet segment, you're routing to a gateway rather than directly to the destination, and no destination-MAC address is available.)

You might read further at: