Example #1
0
MacAddress getMacAddress(const IPv4Address& ipAddr, PcapLiveDevice* pDevice)
{
	// Create an ARP packet and change its fields
	Packet arpRequest(500);

	MacAddress macSrc = pDevice->getMacAddress();
	MacAddress macDst(0xff, 0xff, 0xff, 0xff, 0xff, 0xff);
	EthLayer ethLayer(macSrc, macDst, (uint16_t)PCPP_ETHERTYPE_ARP);
	ArpLayer arpLayer(ARP_REQUEST,
						pDevice->getMacAddress(),
						pDevice->getMacAddress(),
						pDevice->getIPv4Address(),
						ipAddr);


	arpRequest.addLayer(&ethLayer);
	arpRequest.addLayer(&arpLayer);
	arpRequest.computeCalculateFields();

	//setup arp reply filter
	ArpFilter arpFilter(ARP_REPLY);
	pDevice->setFilter(arpFilter);

	//send the arp request and wait for arp reply
	pDevice->sendPacket(&arpRequest);
	RawPacketVector capturedPackets;
	pDevice->startCapture(capturedPackets);
	PCAP_SLEEP(2);
	pDevice->stopCapture();

	if (capturedPackets.size() < 1)
	{
		printf("No arp reply was captured. Couldn't retrieve MAC address for IP %s\n", ipAddr.toString().c_str());
		return MacAddress("");
	}

	//parse arp reply and extract the MAC address
	Packet arpReply(capturedPackets.front());
	if (arpReply.isPacketOfType(ARP))
	{
		return arpReply.getLayerOfType<ArpLayer>()->getSenderMacAddress();
	}
	printf("No arp reply was captured. Couldn't retrieve MAC address for IP %s\n", ipAddr.toString().c_str());
	return MacAddress("");
}