Socket.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. This program is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. */
  13. /*
  14. simple socket handling class for systems with BSD socket API
  15. */
  16. #pragma once
  17. #include <AP_HAL/AP_HAL.h>
  18. #if HAL_OS_SOCKETS
  19. #include <fcntl.h>
  20. #include <unistd.h>
  21. #include <sys/ioctl.h>
  22. #include <sys/socket.h>
  23. #include <netinet/in.h>
  24. #include <netinet/tcp.h>
  25. #include <arpa/inet.h>
  26. #include <sys/select.h>
  27. class SocketAPM {
  28. public:
  29. SocketAPM(bool _datagram);
  30. SocketAPM(bool _datagram, int _fd);
  31. ~SocketAPM();
  32. bool connect(const char *address, uint16_t port);
  33. bool bind(const char *address, uint16_t port);
  34. bool reuseaddress();
  35. bool set_blocking(bool blocking);
  36. bool set_cloexec();
  37. void set_broadcast(void);
  38. ssize_t send(const void *pkt, size_t size);
  39. ssize_t sendto(const void *buf, size_t size, const char *address, uint16_t port);
  40. ssize_t recv(void *pkt, size_t size, uint32_t timeout_ms);
  41. // return the IP address and port of the last received packet
  42. void last_recv_address(const char *&ip_addr, uint16_t &port);
  43. // return true if there is pending data for input
  44. bool pollin(uint32_t timeout_ms);
  45. // return true if there is room for output data
  46. bool pollout(uint32_t timeout_ms);
  47. // start listening for new tcp connections
  48. bool listen(uint16_t backlog);
  49. // accept a new connection. Only valid for TCP connections after
  50. // listen has been used. A new socket is returned
  51. SocketAPM *accept(uint32_t timeout_ms);
  52. private:
  53. bool datagram;
  54. struct sockaddr_in in_addr {};
  55. int fd = -1;
  56. void make_sockaddr(const char *address, uint16_t port, struct sockaddr_in &sockaddr);
  57. };
  58. #endif // HAL_OS_SOCKETS