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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#ifdef _WIN32
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#define BROADCAST_IP "192.168.10.255"
#define PORT 12345
#define MESSAGE "Hello, Broadcast!"
int sock = -1;
int sock_ok = 0;
void *receive_broadcast(void *arg) {
struct sockaddr_in local_addr;
char buffer[256];
int addr_len;
int message_len;
while (sock_ok == 0)
{
}
while (1) {
addr_len = sizeof(local_addr);
// message_len = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&local_addr, &addr_len);
message_len = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (message_len < 0) {
perror("recvfrom");
close(sock);
pthread_exit(NULL);
}
buffer[message_len] = '\0';
printf("Received message from %s: %s\n", inet_ntoa(local_addr.sin_addr), buffer);
}
close(sock);
pthread_exit(NULL);
}
int main() {
struct sockaddr_in broadcast_addr;
int broadcast_enable = 1;
pthread_t receive_thread;
struct sockaddr_in local_addr;
#ifdef _WIN32
WORD wVersionRequested;
WSADATA wsaData;
int err;
char response[100] = {0};
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
{
printf("WSAStartup failed with error: %d\n", err);
return 1;
}
#endif
if (pthread_create(&receive_thread, NULL, receive_broadcast, NULL) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
memset(&local_addr, 0, sizeof(local_addr));
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
local_addr.sin_port = htons(3387);
if (bind(sock, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
perror("bind");
close(sock);
pthread_exit(NULL);
}
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast_enable, sizeof(broadcast_enable)) < 0) {
perror("setsockopt(SO_BROADCAST)");
close(sock);
exit(EXIT_FAILURE);
}
memset(&broadcast_addr, 0, sizeof(broadcast_addr));
broadcast_addr.sin_family = AF_INET;
broadcast_addr.sin_addr.s_addr = inet_addr(BROADCAST_IP);
broadcast_addr.sin_port = htons(PORT);
if(connect(sock, (struct sockaddr*)&broadcast_addr, sizeof(broadcast_addr)) != 0)
{
perror("connect");
close(sock);
exit(EXIT_FAILURE);
}
sock_ok = 1;
while (1) {
// if (sendto(sock, MESSAGE, strlen(MESSAGE), 0, (struct sockaddr*)&broadcast_addr, sizeof(broadcast_addr)) < 0) {
if (send(sock, MESSAGE, strlen(MESSAGE), 0) < 0) {
perror("sendto");
close(sock);
exit(EXIT_FAILURE);
}
printf("Sent message: %s\n", MESSAGE);
sleep(2);
}
close(sock);
return 0;
}
|