arp.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // L2TPNS: arp
  2. #include <string.h>
  3. #include <unistd.h>
  4. #include <net/ethernet.h>
  5. #include <net/if_arp.h>
  6. #include <linux/if_packet.h>
  7. #include <netinet/ip6.h>
  8. #include "dhcp6.h"
  9. #include "l2tpns.h"
  10. /* Most of this code is based on keepalived:vrrp_arp.c */
  11. struct arp_buf {
  12. struct ether_header eth;
  13. struct arphdr arp;
  14. /* Data bit - variably sized, so not present in |struct arphdr| */
  15. unsigned char ar_sha[ETH_ALEN]; /* Sender hardware address */
  16. in_addr_t ar_sip; /* Sender IP address. */
  17. unsigned char ar_tha[ETH_ALEN]; /* Target hardware address */
  18. in_addr_t ar_tip; /* Target ip */
  19. } __attribute__((packed));
  20. void sendarp(int ifr_idx, const unsigned char* mac, in_addr_t ip)
  21. {
  22. int fd;
  23. struct sockaddr_ll sll;
  24. struct arp_buf buf;
  25. CSTAT(sendarp);
  26. STAT(arp_sent);
  27. /* Ethernet */
  28. memset(buf.eth.ether_dhost, 0xFF, ETH_ALEN);
  29. memcpy(buf.eth.ether_shost, mac, ETH_ALEN);
  30. buf.eth.ether_type = htons(ETHERTYPE_ARP);
  31. /* ARP */
  32. buf.arp.ar_hrd = htons(ARPHRD_ETHER);
  33. buf.arp.ar_pro = htons(ETHERTYPE_IP);
  34. buf.arp.ar_hln = ETH_ALEN;
  35. buf.arp.ar_pln = 4; //IPPROTO_ADDR_LEN;
  36. buf.arp.ar_op = htons(ARPOP_REQUEST);
  37. /* Data */
  38. memcpy(buf.ar_sha, mac, ETH_ALEN);
  39. memcpy(&buf.ar_sip, &ip, sizeof(ip));
  40. memcpy(buf.ar_tha, mac, ETH_ALEN);
  41. memcpy(&buf.ar_tip, &ip, sizeof(ip));
  42. /* Now actually send the thing */
  43. fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_RARP));
  44. memset(&sll, 0, sizeof(sll));
  45. sll.sll_family = AF_PACKET;
  46. memcpy(sll.sll_addr, mac, sizeof(sll.sll_addr) - 1);
  47. sll.sll_halen = ETH_ALEN;
  48. sll.sll_ifindex = ifr_idx;
  49. sendto(fd, &buf, sizeof(buf), 0, (struct sockaddr*)&sll, sizeof(sll));
  50. close(fd);
  51. }