]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/net/lwip/Socket/TCPSocketServer.cpp
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / net / lwip / Socket / TCPSocketServer.cpp
1 /* Copyright (C) 2012 mbed.org, MIT License
2  *
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:
8  *
9  * The above copyright notice and this permission notice shall be included in all copies or
10  * substantial portions of the Software.
11  *
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.
17  */
18 #include "TCPSocketServer.h"
19
20 #include <cstring>
21
22 using std::memset;
23 using std::memcpy;
24
25 TCPSocketServer::TCPSocketServer() {
26     
27 }
28
29 int TCPSocketServer::bind(int port) {
30     if (init_socket(SOCK_STREAM) < 0)
31         return -1;
32     
33     struct sockaddr_in localHost;
34     memset(&localHost, 0, sizeof(localHost));
35     
36     localHost.sin_family = AF_INET;
37     localHost.sin_port = htons(port);
38     localHost.sin_addr.s_addr = INADDR_ANY;
39     
40     if (lwip_bind(_sock_fd, (const struct sockaddr *) &localHost, sizeof(localHost)) < 0) {
41         close();
42         return -1;
43     }
44     
45     return 0;
46 }
47
48 int TCPSocketServer::listen(int max) {
49     if (_sock_fd < 0)
50         return -1;
51     
52     if (lwip_listen(_sock_fd, max) < 0) {
53         close();
54         return -1;
55     }
56     
57     return 0;
58 }
59
60 int TCPSocketServer::accept(TCPSocketConnection& connection) {
61     if (_sock_fd < 0)
62         return -1;
63     
64     if (!_blocking) {
65         TimeInterval timeout(_timeout);
66         if (wait_readable(timeout) != 0)
67             return -1;
68     }
69     connection.reset_address();
70     socklen_t newSockRemoteHostLen = sizeof(connection._remoteHost);
71     int fd = lwip_accept(_sock_fd, (struct sockaddr*) &connection._remoteHost, &newSockRemoteHostLen);
72     if (fd < 0)
73         return -1; //Accept failed
74     connection._sock_fd = fd;
75     connection._is_connected = true;
76     
77     return 0;
78 }