|
|
@ -1,17 +1,20 @@ |
|
|
|
#include <unistd.h> |
|
|
|
#include <sys/socket.h> |
|
|
|
#include <netinet/in.h> |
|
|
|
#include <sys/ioctl.h> |
|
|
|
#include <netinet/in.h> |
|
|
|
#include <net/if.h> |
|
|
|
#include <arpa/inet.h> |
|
|
|
#include <errno.h> |
|
|
|
#include <fcntl.h> |
|
|
|
#include <string.h> |
|
|
|
#include <event2/util.h> |
|
|
|
|
|
|
|
#include "Udp.h" |
|
|
|
#include "Log.h" |
|
|
|
|
|
|
|
Udp::Udp() |
|
|
|
:sock(-1), isMcast(false) |
|
|
|
{ |
|
|
|
memset(&destAddr, 0, sizeof destAddr); |
|
|
|
} |
|
|
|
|
|
|
|
int Udp::bind(const char *addr, int p) |
|
|
|
{ |
|
|
|
struct sockaddr_in local_addr; |
|
|
@ -28,9 +31,11 @@ int Udp::open() |
|
|
|
{ |
|
|
|
sock = socket(AF_INET, SOCK_DGRAM, 0); |
|
|
|
if (sock >= 0) { |
|
|
|
evutil_make_socket_nonblocking(sock); |
|
|
|
int reuse = 1; |
|
|
|
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse); |
|
|
|
setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof reuse); |
|
|
|
isMcast = false; |
|
|
|
return 0; |
|
|
|
} |
|
|
|
return -1; |
|
|
@ -47,8 +52,13 @@ int Udp::close() |
|
|
|
|
|
|
|
int Udp::send(const void *buf, int len) |
|
|
|
{ |
|
|
|
if (isMcast) { |
|
|
|
return sendto(sock, buf, len, 0, (struct sockaddr *)&destAddr, |
|
|
|
sizeof destAddr); |
|
|
|
} else { |
|
|
|
return write(sock, buf, len); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
int Udp::recv(void *buf, int len) |
|
|
|
{ |
|
|
@ -79,6 +89,7 @@ int Udp::openMulticast(const char *grp_addr, int port, const char *local) |
|
|
|
goto done; |
|
|
|
} |
|
|
|
|
|
|
|
evutil_make_socket_nonblocking(sock); |
|
|
|
do { |
|
|
|
int reuse = 1; |
|
|
|
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse); |
|
|
@ -117,6 +128,13 @@ int Udp::openMulticast(const char *grp_addr, int port, const char *local) |
|
|
|
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof loop); |
|
|
|
} while (0); |
|
|
|
|
|
|
|
memset(&destAddr, 0, sizeof destAddr); |
|
|
|
|
|
|
|
destAddr.sin_family = AF_INET; |
|
|
|
destAddr.sin_port = htons(port); |
|
|
|
destAddr.sin_addr.s_addr = inet_addr(grp_addr); |
|
|
|
isMcast = true; |
|
|
|
|
|
|
|
sm = 0; |
|
|
|
done: |
|
|
|
return sm; |
|
|
|