void consume_all_sockets(uint8_t protocol) { static int port = 9000; int socket_handle; do { socket_handle = socket_create(AF_INET, SOCK_STREAM, protocol==IPPROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP, port++, NIF_DEFAULT); } while(socket_handle_valid(socket_handle)); }
sock_handle_t start_accept() { sock_handle_t handle = next_unused_tcp(); if (!socket_handle_valid(handle)) return handle; ip::tcp::socket& sock = tcp_from(handle); acceptor.accept(sock); return handle; }
sock_handle_t accept() { sock_handle_t handle = next_unused_tcp(); if (!socket_handle_valid(handle)) return handle; ip::tcp::socket& sock = tcp_from(handle); acceptor.accept(sock, ec); return !ec ? handle : socket_handle_invalid(); }
/** * Discards a previously allocated socket. If the socket is already invalid, returns silently. * Once a socket has been passed to the client, this is the only time the object is * deleted. Since the client initiates this call, the client is aware can the * socket is no longer valid. * @param handle The handle to discard. * @return SOCKET_INVALID always. */ sock_handle_t socket_dispose(sock_handle_t handle) { if (socket_handle_valid(handle)) { socket_t* socket = from_handle(handle); SocketList& list = list_for(socket); /* IMPORTANT: SocketListLock is acquired first */ SocketListLock lock(list); std::lock_guard<socket_t> lk(*socket); if (list.remove(socket)) delete socket; } return SOCKET_INVALID; }
sock_handle_t socket_create(uint8_t family, uint8_t type, uint8_t protocol, uint16_t port, network_interface_t nif) { sock_handle_t sock = socket(family, type, protocol); if (socket_handle_valid(sock)) { if (IPPROTO_UDP==protocol) { bool bound = socket_bind(sock, port) >= 0; DEBUG("socket=%d bound=%d",sock,bound); if(!bound) { socket_close(sock); sock = SOCKET_INVALID; } } } return sock; }