2019-07-14 22:39:37 +00:00
|
|
|
#include <arpa/inet.h>
|
|
|
|
#include <trantor/utils/Logger.h>
|
|
|
|
#include "config.h"
|
|
|
|
#include <unistd.h>
|
2019-09-08 21:42:48 +00:00
|
|
|
#include <helpers.h>
|
2019-07-14 22:39:37 +00:00
|
|
|
|
|
|
|
int
|
2020-02-23 00:12:39 +00:00
|
|
|
helpers::send_udp_broadcast(const char *addr, uint16_t port, void *message, size_t length)
|
2019-07-14 22:39:37 +00:00
|
|
|
{
|
2019-07-20 12:51:45 +00:00
|
|
|
struct sockaddr_in their_addr{};
|
2019-07-14 22:39:37 +00:00
|
|
|
int fd;
|
|
|
|
|
|
|
|
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
|
|
|
|
{
|
|
|
|
LOG_ERROR << "Error creating socket";
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int broadcast = 1;
|
|
|
|
if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast) < 0)
|
|
|
|
{
|
|
|
|
LOG_ERROR << "Error setting broadcast";
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
memset(&their_addr, 0, sizeof(their_addr));
|
|
|
|
their_addr.sin_family = AF_INET;
|
|
|
|
their_addr.sin_port = htons(port);
|
|
|
|
their_addr.sin_addr.s_addr = inet_addr(addr);
|
|
|
|
|
2020-02-23 00:12:39 +00:00
|
|
|
if(sendto(fd, message, length, 0, (struct sockaddr *)&their_addr, sizeof(their_addr)) < 0)
|
2019-07-14 22:39:37 +00:00
|
|
|
{
|
|
|
|
LOG_ERROR << "Error sending broadcast " << errno << " " << strerror(errno);
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
close(fd);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|