pcap_unix.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2012 Google, Inc. All rights reserved.
  2. // Copyright 2009-2011 Andreas Krennmair. All rights reserved.
  3. //
  4. // Use of this source code is governed by a BSD-style license
  5. // that can be found in the LICENSE file in the root of the source
  6. // tree.
  7. //
  8. // +build !windows
  9. package pcap
  10. /*
  11. #include <stdlib.h>
  12. #include <pcap.h>
  13. // pcap_wait returns when the next packet is available or the timeout expires.
  14. // Since it uses pcap_get_selectable_fd, it will not work in Windows.
  15. int pcap_wait(pcap_t *p, int usec) {
  16. fd_set fds;
  17. int fd;
  18. struct timeval tv;
  19. fd = pcap_get_selectable_fd(p);
  20. if(fd < 0) {
  21. return fd;
  22. }
  23. FD_ZERO(&fds);
  24. FD_SET(fd, &fds);
  25. tv.tv_sec = 0;
  26. tv.tv_usec = usec;
  27. if(usec != 0) {
  28. return select(fd+1, &fds, NULL, NULL, &tv);
  29. }
  30. // block indefinitely if no timeout provided
  31. return select(fd+1, &fds, NULL, NULL, NULL);
  32. }
  33. */
  34. import "C"
  35. import (
  36. "errors"
  37. "unsafe"
  38. )
  39. func (p *Handle) setNonBlocking() error {
  40. buf := (*C.char)(C.calloc(errorBufferSize, 1))
  41. defer C.free(unsafe.Pointer(buf))
  42. // Change the device to non-blocking, we'll use pcap_wait to wait until the
  43. // handle is ready to read.
  44. if v := C.pcap_setnonblock(p.cptr, 1, buf); v == -1 {
  45. return errors.New(C.GoString(buf))
  46. }
  47. return nil
  48. }
  49. // waitForPacket waits for a packet or for the timeout to expire.
  50. func (p *Handle) waitForPacket() {
  51. // need to wait less than the read timeout according to pcap documentation.
  52. // timeoutMillis rounds up to at least one millisecond so we can safely
  53. // subtract up to a millisecond.
  54. usec := timeoutMillis(p.timeout) * 1000
  55. usec -= 100
  56. C.pcap_wait(p.cptr, usec)
  57. }