|
| 1 | +/* |
| 2 | +** Project CppSockets, 2022 |
| 3 | +** |
| 4 | +** Author Francois Michaut |
| 5 | +** |
| 6 | +** Started on Sat Jan 15 01:17:42 2022 Francois Michaut |
| 7 | +** Last update Wed Sep 14 22:18:29 2022 Francois Michaut |
| 8 | +** |
| 9 | +** Socket.hpp : Portable C++ socket class |
| 10 | +*/ |
| 11 | + |
| 12 | +#pragma once |
| 13 | + |
| 14 | +#ifdef _WIN32 |
| 15 | +#define NOMINMAX |
| 16 | +#include <winsock2.h> |
| 17 | +using RawSocketType=SOCKET; |
| 18 | +using socklen_t=int; |
| 19 | +#else |
| 20 | +#include <sys/socket.h> |
| 21 | +using RawSocketType=int; |
| 22 | +#endif |
| 23 | + |
| 24 | +#include <memory> |
| 25 | + |
| 26 | +#include "CppSockets/Address.hpp" |
| 27 | + |
| 28 | +namespace CppSockets { |
| 29 | + class Socket { |
| 30 | + public: |
| 31 | + Socket(int domain, int type, int protocol); |
| 32 | + ~Socket(); |
| 33 | + |
| 34 | + Socket(const Socket &other) = delete; |
| 35 | + Socket(Socket &&other) noexcept; |
| 36 | + Socket &operator=(const Socket &other) = delete; |
| 37 | + Socket &operator=(Socket &&other) noexcept; |
| 38 | + |
| 39 | + std::string read(std::size_t len = -1); |
| 40 | + std::size_t read(char *buff, std::size_t size); |
| 41 | + std::size_t write(const std::string &buff); |
| 42 | + std::size_t write(const char *buff, std::size_t len); |
| 43 | + |
| 44 | + int getsockopt(int level, int optname, void *optval, socklen_t *optlen); |
| 45 | + int setsockopt(int level, int optname, const void *optval, socklen_t optlen); |
| 46 | + |
| 47 | + int connect(const IEndpoint &endpoint); |
| 48 | + int connect(const std::string &addr, int port); |
| 49 | + |
| 50 | + int bind(std::uint32_t addr, int port); // TODO remove ? |
| 51 | + int bind(const IEndpoint &endpoint); |
| 52 | + int bind(const std::string &addr, int port); |
| 53 | + int listen(int backlog); |
| 54 | + std::shared_ptr<Socket> accept(void *addr_out); |
| 55 | + |
| 56 | + void set_blocking(bool val); |
| 57 | + |
| 58 | + [[nodiscard]] |
| 59 | + RawSocketType get_fd() const; // TODO check if windows SOCKET can be |
| 60 | + // converted to int |
| 61 | + [[nodiscard]] |
| 62 | + int get_type() const; |
| 63 | + [[nodiscard]] |
| 64 | + int get_domain() const; |
| 65 | + [[nodiscard]] |
| 66 | + int get_protocol() const; |
| 67 | + |
| 68 | + [[nodiscard]] |
| 69 | + bool connected() const; |
| 70 | + private: |
| 71 | + Socket(int domain, int type, int protocol, int sockfd); |
| 72 | + |
| 73 | + static void init(); |
| 74 | + |
| 75 | + static int getsockopt(int fd, int level, int optname, void *optval, socklen_t *optlen); |
| 76 | + static int get_errno(); |
| 77 | + static char *strerror(int err); |
| 78 | + static char *strerror(); |
| 79 | + |
| 80 | + int domain; |
| 81 | + int type; |
| 82 | + int protocol; |
| 83 | + RawSocketType sockfd; |
| 84 | + bool is_connected = false; |
| 85 | + }; |
| 86 | +} |
0 commit comments