Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 1 | #include "aos/vision/events/udp.h" |
| 2 | |
| 3 | #include <string.h> |
| 4 | |
| 5 | #include "aos/common/logging/logging.h" |
| 6 | |
| 7 | namespace aos { |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 8 | namespace events { |
Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 9 | |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 10 | TXUdpSocket::TXUdpSocket(const std::string &ip_addr, int port) |
Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 11 | : fd_(PCHECK(socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))) { |
Brian Silverman | 2ccf8c5 | 2016-03-15 00:22:26 -0400 | [diff] [blame] | 12 | sockaddr_in destination_in; |
| 13 | memset(&destination_in, 0, sizeof(destination_in)); |
Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 14 | destination_in.sin_family = AF_INET; |
| 15 | destination_in.sin_port = htons(port); |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 16 | if (inet_aton(ip_addr.c_str(), &destination_in.sin_addr) == 0) { |
| 17 | LOG(FATAL, "invalid IP address %s\n", ip_addr.c_str()); |
Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 18 | } |
| 19 | |
| 20 | PCHECK(connect(fd_.get(), reinterpret_cast<sockaddr *>(&destination_in), |
| 21 | sizeof(destination_in))); |
| 22 | } |
| 23 | |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 24 | int TXUdpSocket::Send(const char *data, int size) { |
Parker Schuh | 309dd72 | 2017-02-25 11:31:18 -0800 | [diff] [blame^] | 25 | // Don't fail on send. If no one is connected that is fine. |
| 26 | return send(fd_.get(), data, size, 0); |
Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 27 | } |
| 28 | |
| 29 | RXUdpSocket::RXUdpSocket(int port) |
| 30 | : fd_(PCHECK(socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))) { |
Brian Silverman | 2ccf8c5 | 2016-03-15 00:22:26 -0400 | [diff] [blame] | 31 | sockaddr_in bind_address; |
| 32 | memset(&bind_address, 0, sizeof(bind_address)); |
Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 33 | |
| 34 | bind_address.sin_family = AF_INET; |
| 35 | bind_address.sin_port = htons(port); |
| 36 | bind_address.sin_addr.s_addr = htonl(INADDR_ANY); |
| 37 | |
| 38 | PCHECK(bind(fd_.get(), reinterpret_cast<sockaddr *>(&bind_address), |
| 39 | sizeof(bind_address))); |
| 40 | } |
| 41 | |
| 42 | int RXUdpSocket::Recv(void *data, int size) { |
| 43 | return PCHECK(recv(fd_.get(), static_cast<char *>(data), size, 0)); |
| 44 | } |
| 45 | |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 46 | } // namespace events |
Brian Silverman | 4acae81 | 2016-03-14 13:16:19 -0400 | [diff] [blame] | 47 | } // namespace aos |