Skip to content

Instantly share code, notes, and snippets.

@Lomasterrrr
Last active September 20, 2024 11:53
Show Gist options
  • Select an option

  • Save Lomasterrrr/f71c2ad5c2f70d1aaff6e8bf0c121c28 to your computer and use it in GitHub Desktop.

Select an option

Save Lomasterrrr/f71c2ad5c2f70d1aaff6e8bf0c121c28 to your computer and use it in GitHub Desktop.
arp request
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <sys/param.h>
#include <netpacket/packet.h>
#include <net/ethernet.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <netdb.h>
#define DEVICE "enp7s0"
#define SRC_MAC 0x40,0xb0,0x76,0x47,0x8f,0x9a
#define SRC_IP4 192,168,1,33
#define ROUTE_IP4 192,168,1,1
#define ARP_PRO_IP 0x0800
typedef unsigned char u8;
typedef unsigned short u16;
typedef struct __received {
u8 skip[12];
u16 type;
u8 skip1[8];
u8 sha[6];
u8 skip2[4+6];
u8 tpa[4];
} recvhdr;
int main(void)
{
struct sockaddr_ll sll;
struct ifreq ifr;
int fd, n;
char device[] = DEVICE;
size_t pktlen;
u8 pkt[100];
u8 received[100];
recvhdr *r=NULL;
u8 res[6];
/* mac hdr*/
u8 mac_dst[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
u8 mac_src[6] = {SRC_MAC};
u16 mac_type = htons(ETHERTYPE_ARP);
/* arp hdr*/
u16 arp_hdr = htons(ARPHRD_ETHER);
u16 arp_pro = htons(ARP_PRO_IP);
u8 arp_hln = 6; /* mac addr len */
u8 arp_pln = 4; /* ipv4 addr len */
u16 arp_op = htons(ARPOP_REQUEST); /* operation */
/* arp request hdr*/
u8 sha[6] = {SRC_MAC};
u8 spa[4] = {SRC_IP4};
u8 tha[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
u8 tpa[4] = {192, 168, 1, 1};
/* copy */
memcpy(pkt, mac_dst, 6);
memcpy(pkt+6, mac_src, 6);
memcpy(pkt+6+6, &mac_type, 2);
memcpy(pkt+14, &arp_hdr, 2);
memcpy(pkt+14+2, &arp_pro, 2);
memcpy(pkt+14+2+2, &arp_hln, 1);
memcpy(pkt+14+2+2+1, &arp_pln, 1);
memcpy(pkt+14+2+2+1+1, &arp_op, 2);
memcpy(pkt+14+8, sha, 6);
memcpy(pkt+14+8+6, spa, 4);
memcpy(pkt+14+8+6+4, tha, 6);
memcpy(pkt+14+8+6+4+6, tpa, 4);
/* machdr + arphdr + arpreqhdr */
pktlen=14+8+20;
fd=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (fd<0)
return -1;
n=1;
if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &n, sizeof(n))<0)
goto fail;
strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0)
goto fail;
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol=ETHERTYPE_ARP;
sendto(fd, pkt, pktlen, 0, (struct sockaddr*)&sll, sizeof(sll));
for (;;) {
if ((recv(fd, received, 100, 0))==-1)
goto fail;
r=(recvhdr*)received;
if (ntohs(r->type)==ETHERTYPE_ARP) {
#define CMP(x) (r->tpa[(x)]==spa[(x)])
if (CMP(0)&&CMP(1)&&CMP(2)&&CMP(3)) {
memcpy(res, r->sha, 6);
break;
}
#undef CMP
}
}
printf("dst mac is %02x:%02x:%02x:%02x:%02x:%02x\n",
res[0], res[1], res[2], res[3], res[4], res[5]);
close(fd);
return 0;
fail:
close(fd);
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment