-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcast-sender.cpp
57 lines (51 loc) · 1.56 KB
/
mcast-sender.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
//simple multicast sender: specify port and multicast address
//on command line
//compile with -std=c++11
//author: Ugo Varetto
//multicast: from 224.0.0.0 to 239.255.255.255
//see: https://en.wikipedia.org/wiki/Multicast_address
//use 225.x.x.x
//reserved multicast addresses
//http://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring> //memset
#include <string>
#include <iostream>
#include <cstdlib>
#include <thread>
#include <chrono>
using namespace std;
using namespace chrono;
int main(int argc, char** argv) {
if(argc < 3) {
cerr << "usage: " << argv[0] << " <port> <multicast group ip address> [message]"
<< endl;
return EXIT_FAILURE;
}
const int port = stoi(argv[1]);
const string mcastIP = argv[2];
const int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd< 0) {
perror("socket");
exit(EXIT_FAILURE);
}
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(mcastIP.c_str());
addr.sin_port = htons(port);
const string message = argc > 3 ? argv[3] : "Hello Multicast!";
while(true) {
if(sendto(fd, message.c_str(), message.size(), 0,
reinterpret_cast< sockaddr* >(&addr),
sizeof(addr)) < 0) {
perror("sendto");
exit(EXIT_FAILURE);
}
this_thread::sleep_for(seconds(1));
}
return EXIT_SUCCESS;
}