2 * Copyright (C) 2014 John Crispin <blogic@openwrt.org>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License version 2.1
6 * as published by the Free Software Foundation
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #include <sys/socket.h>
15 #include <sys/ioctl.h>
16 #include <sys/types.h>
18 #include <sys/utsname.h>
20 #include <linux/sockios.h>
21 #include <arpa/inet.h>
31 #include <libubox/uloop.h>
37 struct uloop_fd listener
;
40 signal_shutdown(int signal
)
48 signal(SIGPIPE
, SIG_IGN
);
49 signal(SIGTERM
, signal_shutdown
);
50 signal(SIGKILL
, signal_shutdown
);
54 rand_time_delta(uint32_t t
)
57 int fd
= open("/dev/urandom", O_RDONLY
);
62 if (read(fd
, &val
, sizeof(val
)) == sizeof(val
)) {
66 val
= t
+ (rand() % range
) - (range
/ 2);
77 get_iface_ipv4(const char *ifname
)
79 static char buffer
[INET_ADDRSTRLEN
];
84 sock
= socket(AF_INET
, SOCK_DGRAM
, 0);
88 memset(&ir
, 0, sizeof(struct ifreq
));
90 strncpy(ir
.ifr_name
, ifname
, sizeof(ir
.ifr_name
));
92 if (ioctl(sock
, SIOCGIFADDR
, &ir
) < 0)
95 ret
= inet_ntop(AF_INET
, &((struct sockaddr_in
*) &ir
.ifr_addr
)->sin_addr
, buffer
, sizeof(buffer
));
104 static struct utsname utsname
;
106 if (uname(&utsname
) < 0)
109 return utsname
.nodename
;
113 socket_setup(int fd
, const char *ip
)
115 struct ip_mreqn mreq
;
119 struct sockaddr_in sa
;
121 sa
.sin_family
= AF_INET
;
122 sa
.sin_port
= htons(MCAST_PORT
);
123 inet_pton(AF_INET
, MCAST_ADDR
, &sa
.sin_addr
);
125 memset(&mreq
, 0, sizeof(mreq
));
126 mreq
.imr_address
.s_addr
= htonl(INADDR_ANY
);
127 mreq
.imr_multiaddr
= sa
.sin_addr
;
129 if (setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_TTL
, &ttl
, sizeof(ttl
)) < 0)
130 fprintf(stderr
, "ioctl failed: IP_MULTICAST_TTL\n");
132 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(yes
)) < 0)
133 fprintf(stderr
, "ioctl failed: SO_REUSEADDR\n");
135 if (setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &mreq
, sizeof(mreq
)) < 0) {
136 fprintf(stderr
, "failed to join multicast group: %s\n", strerror(errno
));
142 if (setsockopt(fd
, IPPROTO_IP
, IP_RECVTTL
, &yes
, sizeof(yes
)) < 0)
143 fprintf(stderr
, "ioctl failed: IP_RECVTTL\n");
145 if (setsockopt(fd
, IPPROTO_IP
, IP_PKTINFO
, &yes
, sizeof(yes
)) < 0)
146 fprintf(stderr
, "ioctl failed: IP_PKTINFO\n");
148 if (setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
, &no
, sizeof(no
)) < 0)
149 fprintf(stderr
, "ioctl failed: IP_MULTICAST_LOOP\n");
155 memdup(void *d
, int l
)