-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10.BROADCAST_UDP_SERVER.cpp
More file actions
51 lines (46 loc) · 1.1 KB
/
10.BROADCAST_UDP_SERVER.cpp
File metadata and controls
51 lines (46 loc) · 1.1 KB
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
/*
BROADCAST UDP SERVER
*/
#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#efine BROADCAST_ADDRESS "255.255.255.255"
int main()
{
//file descriptors:
int sock_fd;
// string
char str[100];
//socket:
sock_fd=socket(AF_INET,SOCK_DGRAM,0);
if(sock_fd<0){
printf("Error creating socket");
exit(0);
}
//SET FOR BROADCAST:
int broadcast=1;
setsockopt(sock_fd,SOL_SOCKET,SO_BROADCAST,&broadcast,sizeof(broadcast));
//structure:
struct sockaddr_in servaddr,cliaddr;
bzero(&servaddr,sizeof(servaddr))
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(12345);
servaddr.sin_addr.s_addr=inet_addr(BROADCAST_ADDRESS);
//sending so no bind reqd
socklen_t cliLength=sizeof(cliaddr);
//sent broadcast msg:
while(1){
bzero(str,sizeof(str));
fgets(str,sizeof(str),stdin);
sendto(sock_fd,str,sizeof(str),0,(struct sockaddr*)&cliaddr,cliLength);
printf("Broadcasted message: %s",str);
}
close(sock_fd);
return 0;
}