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
) {
19 if ((link
->fd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
)) == -1) {
23 setsockopt(link
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof(one
)); // can multi-bind
24 fcntl(link
->fd
, F_SETFL
, fcntl(link
->fd
, F_GETFL
, 0) | O_NONBLOCK
); // nonblock
26 link
->isServer
= isServer
;
27 memset(&link
->si
, 0, sizeof(link
->si
));
28 link
->si
.sin_family
= AF_INET
;
29 link
->si
.sin_port
= htons(port
);
33 link
->si
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
35 link
->si
.sin_addr
.s_addr
= inet_addr(addr
);
39 if (bind(link
->fd
, (const struct sockaddr
*)&link
->si
, sizeof(link
->si
)) == -1) {
46 int udpSend(udpLink_t
* link
, const void* data
, size_t size
) {
47 return sendto(link
->fd
, data
, size
, 0, (struct sockaddr
*)&link
->si
, sizeof(link
->si
));
50 int udpRecv(udpLink_t
* link
, void* data
, size_t size
, uint32_t timeout_ms
) {
55 FD_SET(link
->fd
, &fds
);
57 tv
.tv_sec
= timeout_ms
/ 1000;
58 tv
.tv_usec
= (timeout_ms
% 1000) * 1000UL;
60 if (select(link
->fd
+1, &fds
, NULL
, NULL
, &tv
) != 1) {
66 ret
= recvfrom(link
->fd
, data
, size
, 0, (struct sockaddr
*)&link
->recv
, &len
);