2 * Copyright (c) 2017 cs8425
4 * This library is free software; you can redistribute it and/or modify it
5 * under the terms of the MIT license.
11 #include <sys/socket.h>
16 int udpInit(udpLink_t
* link
, const char* addr
, int port
, bool isServer
)
20 if ((link
->fd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
)) == -1) {
24 setsockopt(link
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof(one
)); // can multi-bind
25 fcntl(link
->fd
, F_SETFL
, fcntl(link
->fd
, F_GETFL
, 0) | O_NONBLOCK
); // nonblock
27 link
->isServer
= isServer
;
28 memset(&link
->si
, 0, sizeof(link
->si
));
29 link
->si
.sin_family
= AF_INET
;
30 link
->si
.sin_port
= htons(port
);
34 link
->si
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
36 link
->si
.sin_addr
.s_addr
= inet_addr(addr
);
40 if (bind(link
->fd
, (const struct sockaddr
*)&link
->si
, sizeof(link
->si
)) == -1) {
47 int udpSend(udpLink_t
* link
, const void* data
, size_t size
)
49 return sendto(link
->fd
, data
, size
, 0, (struct sockaddr
*)&link
->si
, sizeof(link
->si
));
52 int udpRecv(udpLink_t
* link
, void* data
, size_t size
, uint32_t timeout_ms
)
58 FD_SET(link
->fd
, &fds
);
60 tv
.tv_sec
= timeout_ms
/ 1000;
61 tv
.tv_usec
= (timeout_ms
% 1000) * 1000UL;
63 if (select(link
->fd
+1, &fds
, NULL
, NULL
, &tv
) != 1) {
69 ret
= recvfrom(link
->fd
, data
, size
, 0, (struct sockaddr
*)&link
->recv
, &len
);