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

浪子不回头ぞ 提交于 2019-12-21 05:11:18

问题


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?


回答1:


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:

  • http://linux.die.net/man/8/arp
  • http://linux.die.net/man/8/arping
  • http://linux.die.net/man/7/arp
  • http://www.kernel.org/doc/man-pages/online/pages/man7/arp.7.html



回答2:


Obviously you can only find the MAC address for directly connected IP addresses, but there's no platform-independent way of doing it. On Linux, you can look in /proc/net/arp after sending something to the target to trigger the kernel to send the ARP.

Edit to add you could also use the SIOCGARP ioctl() though that just looks in the ARP cache, so it won't send an ARP if there isn't one already there.

Otherwise, you would have to craft your own ARP request packet. You could probably reuse a bunch of code from arping if you go that route.




回答3:


You cannot in general get the MAC address from the IP address, and in fact as IP can run on data link protocols other than ethernet, some IP addresses have no corresponding MAC address.

The MAC address is only available and only relevant on the same ethernet segment. On that segment, it can be retrieved by an ARP request.



来源:https://stackoverflow.com/questions/4480689/resolving-mac-address-for-ip-address-using-c-on-linux

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