forked from svpcom/wfb-ng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wifibroadcast.cpp
71 lines (61 loc) · 2.27 KB
/
wifibroadcast.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright (C) 2017 - 2022 Vasily Evseenko <[email protected]>
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdlib.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <memory>
#include <stdexcept>
#include "wifibroadcast.hpp"
using namespace std;
string string_format(const char *format, ...)
{
va_list args;
va_start(args, format);
size_t size = vsnprintf(nullptr, 0, format, args) + 1; // Extra space for '\0'
va_end(args);
unique_ptr<char[]> buf(new char[size]);
va_start(args, format);
vsnprintf(buf.get(), size, format, args);
va_end(args);
return string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
uint64_t get_time_ms(void) // in milliseconds
{
struct timespec ts;
int rc = clock_gettime(CLOCK_MONOTONIC, &ts);
if (rc < 0) throw runtime_error(string_format("Error getting time: %s", strerror(errno)));
return ts.tv_sec * 1000LL + ts.tv_nsec / 1000000;
}
int open_udp_socket_for_rx(int port)
{
struct sockaddr_in saddr;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) throw runtime_error(string_format("Error opening socket: %s", strerror(errno)));
int optval = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int));
bzero((char *) &saddr, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons((unsigned short)port);
if (bind(fd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0)
{
throw runtime_error(string_format("Bind error: %s", strerror(errno)));
}
return fd;
}