views:

781

answers:

2

Currently we're parsing arp request output from the command line.

string cmd = "arp -n ";
cmd.append(ipaddress);
cmd.append(" | grep ");
cmd.append(ipaddress);
fgets( line, 130, fp);
fgets( line, 130, fp);
ret.append(line);
 ...

It works, but is there a way to do this using a library function that wont depend so much on the native command line interface? The project is using libpcap currently.

+1  A: 

In general, this will depend on your OS. There's no real standard API for this.

Assuming you're on linux, open and parse /proc/net/arp. The format is similar to that of the output from the arp command. Note that you must send a packet to the IP in question at least once recently in order to have it in the ARP table, and of course you won't get anything outside of your local segment.

Getting an IP into this cache is easy enough - just send a UDP packet to it on some unused port, for example - then poll until it shows up.

Another alternative would be to use a raw socket to craft and send your own arp packet, but that's much more complex :) If you do want to go down this route, study the source code for arping (page is down today, but the git repo is online), which might also give you a bit more portability by using platform-independent-ish libraries like libpcap (but requires root)

bdonlan
But that is the arp cache, so it would only work if we had send a request to that IP before. However, that does provide a more platform independent way of reading it in after submitting the request.
greenguy1090
It's not more platform independent. There is no platform independent way. And if you want to send a request to that IP it's easy enough - just throw some random UDP packet at it.
bdonlan
I'm sorry, its more distro independent. I misspoke.
greenguy1090
I'm going to give this a look, as we already need root for this project anyway. Thanks!
greenguy1090
+1  A: 

I am a little worried about the

retrieve foreign host’s MAC address

part of your question.

I hope that you are aware that you only get entries in the ARP table for machines on the same network. If you connect to a machine via a router then you will only see the routers MAC address in the ARP table. So there is no way of knowing the foreign host’s MAC address unless it's a host on the same network (no routers involved).

So the answer is that it is impossible for hosts that are reached via a router and in case the host is reachable on the local network you can use only platform specific access methods, as even the output of the arp command may differ between platforms.

lothar