Skip to content

Instantly share code, notes, and snippets.

@pavi2410
Created October 3, 2021 17:08
Show Gist options
  • Save pavi2410/8155fffe605176d1a18cd300e64a369e to your computer and use it in GitHub Desktop.
Save pavi2410/8155fffe605176d1a18cd300e64a369e to your computer and use it in GitHub Desktop.
Get MAC address using IP address via ARP using UDP sockets
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
struct sockaddr_in sin = {0};
sin.sin_family = AF_INET;
char ip[20];
printf("Enter IP address: ");
scanf("%s", ip);
if(inet_pton(AF_INET, ip, &sin.sin_addr) == 0) {
printf("Invalid IP address = %s entered.\n", ip);
return 1;
}
struct arpreq myarp = {{0}};
memcpy(&myarp.arp_pa, &sin, sizeof(myarp.arp_pa));
strcpy(myarp.arp_dev, "eth0");
int sd;
if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket");
return 1;
}
printf("Sending ARP request...\n");
if(ioctl(sd, SIOCGARP, &myarp) < 0) {
printf("No entry in ARP cache for %s!\n",ip);
exit(1);
}
close(sd);
unsigned char *mac = myarp.arp_ha.sa_data;
printf("Received ARP reply...\n");
printf("MAC address for %s is ", ip);
printf("%02X:%02X:%02X:%02X:%02X:%02X\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return 0;
}
@pavi2410
Copy link
Author

pavi2410 commented Oct 3, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment