socket-bsd.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. #include "socket.h"
  9. #include <errno.h>
  10. #include "../lib/includes.h"
  11. #include "../lib/logger.h"
  12. #include <sys/types.h>
  13. #include <sys/time.h>
  14. #include <sys/ioctl.h>
  15. #include <fcntl.h>
  16. #include <net/bpf.h>
  17. #include "state.h"
  18. sock_t get_socket(UNUSED uint32_t id)
  19. {
  20. char file[32];
  21. int bpf;
  22. // Assume failure
  23. sock_t ret;
  24. ret.sock = -1;
  25. // Try to find a valid bpf
  26. for (int i = 0; i < 128; i++) {
  27. snprintf(file, sizeof(file), "/dev/bpf%d", i);
  28. bpf = open(file, O_WRONLY);
  29. if (bpf != -1 || errno != EBUSY)
  30. break;
  31. }
  32. // Make sure it worked
  33. if (bpf < 0) {
  34. return ret;
  35. }
  36. // Set up an ifreq to bind to
  37. struct ifreq ifr;
  38. memset(&ifr, 0, sizeof(ifr));
  39. strlcpy(ifr.ifr_name, zconf.iface, sizeof(ifr.ifr_name));
  40. // Bind the bpf to the interface
  41. if (ioctl(bpf, BIOCSETIF, (char *) &ifr) < 0) {
  42. return ret;
  43. }
  44. // Enable writing the address in
  45. int write_addr_enable = 1;
  46. if (ioctl(bpf, BIOCSHDRCMPLT, &write_addr_enable) < 0) {
  47. return ret;
  48. }
  49. ret.sock = bpf;
  50. return ret;
  51. }