-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBroadcast.cpp
92 lines (72 loc) · 2.36 KB
/
Broadcast.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
// Created by Michał Wilczyński on 6/7/18.
//
#include "Broadcast.h"
#define SERVERPORT 4950 // the port users will be connecting to
void Broadcast::sendDiscoverPacket()
{
if ((he=gethostbyname("255.255.255.255")) == NULL) { // get the host info
perror("gethostbyname");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket");
exit(1);
}
// this call is what allows broadcast packets to be sent:
if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast,
sizeof broadcast) == -1) {
perror("setsockopt (SO_BROADCAST)");
exit(1);
}
their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(SERVERPORT); // short, network byte order
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
if ((numbytes=sendto(sockfd, "RANDOM MESSAGE", strlen("RANDOM MESSAGE"), 0,
(struct sockaddr *)&their_addr, sizeof their_addr)) == -1) {
perror("sendto");
exit(1);
}
printf("sent %d bytes to %s\n", numbytes,
inet_ntoa(their_addr.sin_addr));
close(sockfd);
}
void Broadcast::addNeighbor(sockaddr_in addr)
{
mtx.lock();
addrEntry temporary(std::chrono::system_clock::now(), addr);
for(auto it : neighbors) {
if (it == temporary) {
mtx.unlock();
return;
}
}
neighbors.push_back(addrEntry(std::chrono::system_clock::now(), addr));
mtx.unlock();
}
void Broadcast::listenForDiscoverPackets()
{
sockaddr_in si_me, si_other;
int s;
s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int port=SERVERPORT;
int broadcast=1;
setsockopt(s, SOL_SOCKET, SO_BROADCAST,
&broadcast, sizeof broadcast);
memset(&si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(port);
si_me.sin_addr.s_addr = INADDR_ANY;
bind(s, (sockaddr *)&si_me, sizeof(sockaddr));
while(1)
{
char buf[10000];
unsigned slen=sizeof(sockaddr);
recvfrom(s, buf, sizeof(buf)-1, 0, (sockaddr *)&si_other, &slen);
addNeighbor(si_other);
//inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
// check for hash
printf("recv: %s\n", buf);
}
}