core-legacy/helpers/send_udp_broadcast.cc
Tobias Reisinger a38a6e63b3 add: filters
add: schedule api calls
2019-07-20 14:51:45 +02:00

40 lines
1,020 B
C++

#include <netdb.h>
#include <arpa/inet.h>
#include <trantor/utils/Logger.h>
#include "config.h"
#include <helpers.h>
#include <unistd.h>
int
helpers::send_udp_broadcast(const char *addr, uint16_t port, const char* message)
{
struct sockaddr_in their_addr{};
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);
if(sendto(fd, message, strlen(message), 0, (struct sockaddr *)&their_addr, sizeof(their_addr)) < 0)
{
LOG_ERROR << "Error sending broadcast " << errno << " " << strerror(errno);
return -1;
}
close(fd);
return 0;
}