问题
I need to store persistent reference to third party device on an arbitrary IP network where the IP address of the devices may be static or randomly assigned by DHCP. I don't control the devices on the network and I can't rely on DNS and other ad-hoc networking protocols existing or working with the devices.
So I have been instructed to investigate using hardware addresses and ARP. This will work but I don't want to duplicate code. The kernel must manage an ARP table. On Windows you can access it using GetIpNetTable etc.
I am hoping there is an API to answer these two questions:
- How do I translate from IP to MAC address? (ARP)
- How do I translate from MAC to IP address? (InARP)
If not then I may have to do it more manually:
- How do I read the kernel's ARP table?
- How do I add an entry if I have the determined a mapping myself?
回答1:
/proc/net/arp
K
回答2:
ARP tables tend to be fairly local and short-lived. If you examine the protocol, the real MAC addresses are generally only provided when the given IP address is in the local subnet. Otherwise, the packet is forwarded to the local router, which is then responsible for forwarding it.
If you do "arp -g
" on Windows or "arp -a
" on UNIX, you'll see the table, but I don't think it will do you any good, due to the reasons mentioned above. That command and
That's really what DNS is for but, as you say, it may not be an option for you.
You may well have to write your own 'ARP' database at your application level.
回答3:
As for ARP:
You could use system("/usr/bin/arp -option_of_choice"); and parse the output, but that's an ugly hack. -- Not my recommendation.
Take a look at /usr/include/linux/sockios.h -- At the SIOCGARP, SIOCDARP, and SIOCSARP details. Those are ioctls that you can perform to manage the ARP table on linux. Of course, you'll have to perform these ioctls on a socket fd.
Here's some examples: SIOCGARP examples
I'm sure you can find many other examples in several other languages as well. As I'm assuming that you're using C.
As for RARP:
A quote from the linux rarp manpage:
" This program is obsolete. From version 2.3, the Linux kernel no longer
contains RARP support. For a replacement RARP daemon, see ftp://ftp.demen-
tia.org/pub/net-tools"
So you'll have to install rarpd on the target system.
来源:https://stackoverflow.com/questions/463722/doing-arp-and-inverse-arp-on-linux-2-6-21-glibc-2-3-5