Getting MAC address from Ethernet packet in C++
Hi,
I am writing a C++ program to receive UDP datagrams and I need to know not only the IP address of the computer that sent the datagram but also the MAC address. What I do is to create a socket: int sockd; sockd = socket(PF_INET, SOCK_DGRAM, 0); Then bind it to a port and ip adress: struct sockaddr_in sin; .... populate sin with port, ip_address, etc... bind(sockd,(struct sockaddr *)&sin, sizeof(sin)); Then wait for an UDP datagram: int dsize, sin_len; char buff[256]; dsize = recvfrom(sockd,buff,256,0(struct sockaddr *)&sin, (socklen_t *)&sin_len); And to get the IP address I do: std::cout << "\nIP: " << inet_ntoa(sin.sin_addr); But, do any one knows how to get the MAC of the equipment that generated the UDP datagram I received? I know the MAC address is on the ARP table as it is inserted in it together with the corresponding IP when a Ethernet packet is received for that IP for the first time, but it would be great to get it from the Ethernet header itself to save time, as my program will be doing this several thousands of times per minute. Thanks in advance, Jorge |
I'm not really an expert in network programming, but I know that nmap does such a thing so you could take a look at nmap source. Get it at http://insecure.org/nmap/.
|
heres a code snipplet which i copied and pasted from somewhere quite some time ago(i couldnt locate the original web link to the source) , i think is in c , can get the mac address(from internal lan only ??) ..
Code:
#include <stdlib.h> hope it helps you in some way ... . |
Here's an algorithm, not requiring SOCK_RAW (SOCK_RAW is possible only as root)
http://www.linuxquestions.org/questi...47#post2094647 |
Thanks nx5000,
I took a look at that solution and looks great in case I cannot run the tool as root. Regards, Jorge |
Thanks a lot alred,
I used the code you sent me and worked great. It had a lot of not-needed code. So here it is without the extra code, for future references. Code:
#include <iostream> Jorge |
hi!
can someone help me to transform the sniffer code of eljofi, with the promiscuous mode? i try but not work properly. thank you in advance ;) |
http://www.daniweb.com/forums/thread196899.html
For anyone looking into using this. Quote:
|
correction
The IP dst and src are mixed.
I also don't see the point in checking ethhead; it is from a static buffer; better check number of received bytes. I fixed it, see below. Mark that this shows the MAC source and destination addresses from the received packet. The destination address should be from the device were this program is running. But if you need the MAC address of your device, use ioctl( s, SIOCGIFHWADDR, &ifr ) instead as pointed out in another reply. Regards, Juergen Quote:
|
For the more curious, here is one link to the entire format.
http://en.wikipedia.org/wiki/Ethernet_frame OK |
All times are GMT -5. The time now is 04:18 PM. |