1 // Copyright 2020 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <arpa/inet.h> 17 #include <netinet/in.h> 18 #include <stdio.h> 19 #include <sys/socket.h> 20 #include <unistd.h> 21 22 #include <array> 23 #include <cstddef> 24 #include <limits> 25 #include <span> 26 27 #include "pw_stream/stream.h" 28 29 namespace pw::stream { 30 31 static constexpr int kExitCode = -1; 32 static constexpr int kInvalidFd = -1; 33 34 class SocketStream : public Writer, public Reader { 35 public: SocketStream()36 explicit SocketStream() {} 37 ~SocketStream(); 38 39 // Listen to the port and return after a client is connected 40 Status Serve(uint16_t port); 41 42 // Connect to a local or remote endpoint. Host must be an IPv4 address. If 43 // host is nullptr then the locahost address is used instead. 44 Status Connect(const char* host, uint16_t port); 45 46 // Close the socket stream and release all resources 47 void Close(); 48 49 private: 50 Status DoWrite(std::span<const std::byte> data) override; 51 52 StatusWithSize DoRead(ByteSpan dest) override; 53 54 uint16_t listen_port_ = 0; 55 int socket_fd_ = kInvalidFd; 56 int conn_fd_ = kInvalidFd; 57 struct sockaddr_in sockaddr_client_; 58 }; 59 60 } // namespace pw::stream 61