send-linux.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * ZMap Copyright 2013 Regents of the University of Michigan
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy
  6. * of the License at http://www.apache.org/licenses/LICENSE-2.0
  7. */
  8. #ifndef ZMAP_SEND_LINUX_H
  9. #define ZMAP_SEND_LINUX_H
  10. #include "../lib/includes.h"
  11. #include <sys/ioctl.h>
  12. #include <netpacket/packet.h>
  13. #ifdef ZMAP_SEND_BSD_H
  14. #error "Don't include both send-bsd.h and send-linux.h"
  15. #endif
  16. // Dummy sockaddr for sendto
  17. static struct sockaddr_ll sockaddr;
  18. int send_run_init(sock_t s)
  19. {
  20. // Get the actual socket
  21. int sock = s.sock;
  22. // get source interface index
  23. struct ifreq if_idx;
  24. memset(&if_idx, 0, sizeof(struct ifreq));
  25. if (strlen(zconf.iface) >= IFNAMSIZ) {
  26. log_error("send", "device interface name (%s) too long\n",
  27. zconf.iface);
  28. return EXIT_FAILURE;
  29. }
  30. strncpy(if_idx.ifr_name, zconf.iface, IFNAMSIZ-1);
  31. if (ioctl(sock, SIOCGIFINDEX, &if_idx) < 0) {
  32. perror("SIOCGIFINDEX");
  33. return EXIT_FAILURE;
  34. }
  35. int ifindex = if_idx.ifr_ifindex;
  36. // find source IP address associated with the dev from which we're sending.
  37. // while we won't use this address for sending packets, we need the address
  38. // to set certain socket options and it's easiest to just use the primary
  39. // address the OS believes is associated.
  40. struct ifreq if_ip;
  41. memset(&if_ip, 0, sizeof(struct ifreq));
  42. strncpy(if_ip.ifr_name, zconf.iface, IFNAMSIZ-1);
  43. if (ioctl(sock, SIOCGIFADDR, &if_ip) < 0) {
  44. perror("SIOCGIFADDR");
  45. return EXIT_FAILURE;
  46. }
  47. // destination address for the socket
  48. memset((void*) &sockaddr, 0, sizeof(struct sockaddr_ll));
  49. sockaddr.sll_ifindex = ifindex;
  50. sockaddr.sll_halen = ETH_ALEN;
  51. memcpy(sockaddr.sll_addr, zconf.gw_mac, ETH_ALEN);
  52. return EXIT_SUCCESS;
  53. }
  54. int send_packet(sock_t sock, void *buf, int len, UNUSED uint32_t idx)
  55. {
  56. return sendto(sock.sock, buf, len, 0,
  57. (struct sockaddr *) &sockaddr,
  58. sizeof(struct sockaddr_ll));
  59. }
  60. #endif /* ZMAP_SEND_LINUX_H */