-
Notifications
You must be signed in to change notification settings - Fork 69
/
udpclient.c
67 lines (56 loc) · 1.47 KB
/
udpclient.c
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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
// #include <sys/time.h>
//for Mac OS X
// #include <stdlib.h>
void UDPSend(char *message, int port)
{
if (port > 0)
{
int sd, rc;
struct sockaddr_in cliAddr, remoteServAddr;
struct hostent *h;
int broadcast = 1;
h = gethostbyname("255.255.255.255");
remoteServAddr.sin_family = h->h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
remoteServAddr.sin_port = htons(port);
// socket creation
sd = socket(AF_INET,SOCK_DGRAM,0);
if (sd<0)
{
// printf("Cannot open socket on port %d\n", port);
return;
}
if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &broadcast,sizeof broadcast) == -1)
{
// printf("setsockopt (SO_BROADCAST)");
return;
}
// bind any port
cliAddr.sin_family = AF_INET;
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(0);
rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
if (rc<0)
{
// printf("%s: cannot bind port\n", argv[0]);
return;
}
// send data
rc = sendto(sd, message, strlen(message), 0, (struct sockaddr *) &remoteServAddr, sizeof(remoteServAddr));
if (rc<0)
{
// printf("%s: cannot send data %d \n",argv[0],i-1);
close(sd);
return;
}
close(sd);
}
}