Created
October 3, 2021 17:08
-
-
Save pavi2410/8155fffe605176d1a18cd300e64a369e to your computer and use it in GitHub Desktop.
Get MAC address using IP address via ARP using UDP sockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Short URL: https://git.io/arp_mac