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.
18 #include "Socket/Socket.h"
23 Socket::Socket() : _sock_fd(-1), _blocking(true), _timeout(1500) {
27 void Socket::set_blocking(bool blocking, unsigned int timeout) {
32 int Socket::init_socket(int type) {
36 int fd = lwip_socket(AF_INET, type, 0);
44 int Socket::set_option(int level, int optname, const void *optval, socklen_t optlen) {
45 return lwip_setsockopt(_sock_fd, level, optname, optval, optlen);
48 int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen) {
49 return lwip_getsockopt(_sock_fd, level, optname, optval, optlen);
52 int Socket::select(struct timeval *timeout, bool read, bool write) {
55 FD_SET(_sock_fd, &fdSet);
57 fd_set* readset = (read ) ? (&fdSet) : (NULL);
58 fd_set* writeset = (write) ? (&fdSet) : (NULL);
60 int ret = lwip_select(FD_SETSIZE, readset, writeset, NULL, timeout);
61 return (ret <= 0 || !FD_ISSET(_sock_fd, &fdSet)) ? (-1) : (0);
64 int Socket::wait_readable(TimeInterval& timeout) {
65 return select(&timeout._time, true, false);
68 int Socket::wait_writable(TimeInterval& timeout) {
69 return select(&timeout._time, false, true);
72 int Socket::close(bool shutdown) {
77 lwip_shutdown(_sock_fd, SHUT_RDWR);
85 close(); //Don't want to leak
88 TimeInterval::TimeInterval(unsigned int ms) {
89 _time.tv_sec = ms / 1000;
90 _time.tv_usec = (ms - (_time.tv_sec * 1000)) * 1000;