]>
git.gir.st - tmk_keyboard.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/net/lwip/Socket/UDPSocket.cpp
1 /* Copyright (C) 2012 mbed.org, MIT License
3 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
4 * and associated documentation files (the "Software"), to deal in the Software without restriction,
5 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
6 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
7 * furnished to do so, subject to the following conditions:
9 * The above copyright notice and this permission notice shall be included in all copies or
10 * substantial portions of the Software.
12 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
13 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 #include "Socket/UDPSocket.h"
25 UDPSocket::UDPSocket() {
28 int UDPSocket::init(void) {
29 return init_socket(SOCK_DGRAM
);
32 // Server initialization
33 int UDPSocket::bind(int port
) {
34 if (init_socket(SOCK_DGRAM
) < 0)
37 struct sockaddr_in localHost
;
38 std::memset(&localHost
, 0, sizeof(localHost
));
40 localHost
.sin_family
= AF_INET
;
41 localHost
.sin_port
= htons(port
);
42 localHost
.sin_addr
.s_addr
= INADDR_ANY
;
44 if (lwip_bind(_sock_fd
, (const struct sockaddr
*) &localHost
, sizeof(localHost
)) < 0) {
52 int UDPSocket::join_multicast_group(const char* address
) {
55 // Set up group address
56 mreq
.imr_multiaddr
.s_addr
= inet_addr(address
);
57 mreq
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
59 return set_option(IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &mreq
, sizeof(mreq
));
62 int UDPSocket::set_broadcasting(bool broadcast
) {
63 int option
= (broadcast
) ? (1) : (0);
64 return set_option(SOL_SOCKET
, SO_BROADCAST
, &option
, sizeof(option
));
67 // -1 if unsuccessful, else number of bytes written
68 int UDPSocket::sendTo(Endpoint
&remote
, char *packet
, int length
) {
73 TimeInterval
timeout(_timeout
);
74 if (wait_writable(timeout
) != 0)
78 return lwip_sendto(_sock_fd
, packet
, length
, 0, (const struct sockaddr
*) &remote
._remoteHost
, sizeof(remote
._remoteHost
));
81 // -1 if unsuccessful, else number of bytes received
82 int UDPSocket::receiveFrom(Endpoint
&remote
, char *buffer
, int length
) {
87 TimeInterval
timeout(_timeout
);
88 if (wait_readable(timeout
) != 0)
91 remote
.reset_address();
92 socklen_t remoteHostLen
= sizeof(remote
._remoteHost
);
93 return lwip_recvfrom(_sock_fd
, buffer
, length
, 0, (struct sockaddr
*) &remote
._remoteHost
, &remoteHostLen
);