Question

I'm writing an application that injects packets using SharpPcap.

However, since I'm constructing the packets on my own and only know the destination's IP address, I have to determine the physical address of the next hop. I can always send a ping to the remote IP address, sniff it, and get the MAC address from the sniffed packet. However, I was hoping there's a less convoluted way to do so in C#.

Obviously, getting the next hop's IP address will also be very helpful, as I can then use SendArp to determine its MAC address.

Getting the routing table will do. How would I obtain that using code?

Was it helpful?

Solution

I had some troubles with WMI (it seems that one cannot correlate between an interface-index in Win32_IP4RouteTable with an actual device; MSDN documentation is wrong, and other more hackish techniques fail on some computers).

So, I chose to use the unmanaged GetBestRoute, which actually saved me a lot of time, because it lets Windows do the routing decision on itself, and returns the next hop's IP address and the NIC identifier leading to that address. It's also quite a lot faster than running a query against WMI.

You can then find the NIC itself, by looking for that identifier in the list returned by GetAdaptersInfo.

Hope it helps ...

OTHER TIPS

Physical addresses are resolved by the Address Resolution Protocol - just send an ARP Reuest with the IP address to resolve.

If the destination is not in the local network, the packet must be send to the standard gateway and one must perform an ARP Request for the standard gateway. The standard gateway can be obtained by using methods from the System.Net.NetworkInformation namespace.

 NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses

The completely hackish way of doing it would be to run the command "arp -a" and read and parse the results of the command (using the ARP cache already held by Windows).

Otherwise, you need to include ARP in your protocol stack. This is how your system itself works to figure out where to send frames. Or lastly if you're not worried about being inefficient, you can set your Ethernet destination as: FF:FF:FF:FF:FF:FF and flood everyone on the same LAN as you. When something responds or you get a packet, cache it yourself to have the proper destination MAC address.

Personally, if you did the flood everyone approach on my network, I'd hurt you, but depending on your situation it might be a fairly easy hack. However, doing a 100% full stack implementation is fairly complex, since there are a lot of edge cases that should be well supported (such as handling proxy ARP, gratuitous ARP, etc.).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top