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
|
/*
* Socket operations for wellenreiter
*
* $Id$
*/
#include "sock.hh"
#include "log.hh"
/* Setup UDP Socket for incoming commands */
int commsock(const char *host, int port)
{
struct sockaddr_in saddr;
int sock;
if((sock=socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
wl_logerr("Cannot set up socket: %s", strerror(errno));
return -1;
}
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = PF_INET;
saddr.sin_port = htons(port);
saddr.sin_addr.s_addr = inet_addr(host);
if(bind(sock,(struct sockaddr *)&saddr, sizeof(saddr)) < 0)
{
wl_logerr("Cannot bind socket: %s", strerror(errno));
close(sock);
return -1;
}
return sock;
}
/* Send a string to commsock */
int sendcomm(const char *host, int port, const char *string, ...)
{
int sock;
char buffer[4096];
struct sockaddr_in saddr;
va_list ap;
/* Generate string */
memset(buffer, 0, sizeof(buffer));
va_start(ap, string);
vsnprintf(buffer, sizeof(buffer)-1, string, ap);
va_end(ap);
/* Setup socket */
if((sock=socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
wl_logerr("Cannot set up socket: %s", strerror(errno));
return -1;
}
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
saddr.sin_addr.s_addr = inet_addr(host);
if(sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
{
wl_logerr("Cannot write to socket: %s", strerror(errno));
close(sock);
return 0;
}
if(close(sock) < 0)
wl_logerr("Cannot close socket: %s", strerror(errno));
return 1;
}
|