-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathudp.cpp
More file actions
51 lines (40 loc) · 877 Bytes
/
udp.cpp
File metadata and controls
51 lines (40 loc) · 877 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <cstring>
#include <stdexcept>
#include <string_view>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include "udp.hpp"
namespace multicast
{
namespace udp
{
Socket::Socket()
{
fd_ = socket(AF_INET, SOCK_DGRAM, 0);
if (fd_ < 0)
{
throw std::runtime_error("failed to open UDP socket");
}
}
int Socket::Handler() const noexcept
{
return fd_;
}
Socket::~Socket() noexcept
{
close(fd_);
}
bool send(const Socket& socket, const sockaddr_in& address,
std::string_view message)
{
sockaddr addr{};
static_assert(sizeof(addr) == sizeof(address));
std::memcpy(&addr, &address, sizeof(addr));
const ssize_t sent = sendto(socket.Handler(), message.data(),
message.size(), 0, &addr, sizeof(addr));
return sent >= 0;
}
} // namespace udp
} // namespace multicast