APM:Libraries
Socket.h
Go to the documentation of this file.
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 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program. If not, see <http://www.gnu.org/licenses/>.
14  */
15 /*
16  simple socket handling class for systems with BSD socket API
17  */
18 #pragma once
19 
20 #include <AP_HAL/AP_HAL.h>
21 #if HAL_OS_SOCKETS
22 
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
27 #include <netinet/in.h>
28 #include <netinet/tcp.h>
29 #include <arpa/inet.h>
30 #include <sys/select.h>
31 
32 class SocketAPM {
33 public:
34  SocketAPM(bool _datagram);
35  SocketAPM(bool _datagram, int _fd);
36  ~SocketAPM();
37 
38  bool connect(const char *address, uint16_t port);
39  bool bind(const char *address, uint16_t port);
40  void reuseaddress();
41  void set_blocking(bool blocking);
42  void set_broadcast(void);
43 
44  ssize_t send(const void *pkt, size_t size);
45  ssize_t sendto(const void *buf, size_t size, const char *address, uint16_t port);
46  ssize_t recv(void *pkt, size_t size, uint32_t timeout_ms);
47 
48  // return the IP address and port of the last received packet
49  void last_recv_address(const char *&ip_addr, uint16_t &port);
50 
51  // return true if there is pending data for input
52  bool pollin(uint32_t timeout_ms);
53 
54  // return true if there is room for output data
55  bool pollout(uint32_t timeout_ms);
56 
57  // start listening for new tcp connections
58  bool listen(uint16_t backlog);
59 
60  // accept a new connection. Only valid for TCP connections after
61  // listen has been used. A new socket is returned
62  SocketAPM *accept(uint32_t timeout_ms);
63 
64 private:
65  bool datagram;
66  struct sockaddr_in in_addr {};
67 
68  int fd = -1;
69 
70  void make_sockaddr(const char *address, uint16_t port, struct sockaddr_in &sockaddr);
71 };
72 
73 #endif // HAL_OS_SOCKETS