diff --git a/include/shared_fd.hpp b/include/shared_fd.hpp index 6bc81a8..c1067c1 100644 --- a/include/shared_fd.hpp +++ b/include/shared_fd.hpp @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include #include @@ -47,6 +49,31 @@ namespace gp{ sticky_bit = S_ISVTX, }; + enum class net_socket_domain : int { + ip4 = AF_INET, + ip6 = AF_INET6 + }; + + enum class net_socket_protocol : int { + tcp = SOCK_STREAM, + udp = SOCK_DGRAM + }; + + + using socket_opt_flags = int; + + enum class net_socket_opt_flags : socket_opt_flags { + non_blocking = SOCK_NONBLOCK, + close_on_exec = SOCK_CLOEXEC, + }; + + using socket_opt_flags = int; + + enum class unix_socket_opt_flags : socket_opt_flags { + non_blocking = SOCK_NONBLOCK, + close_on_exec = SOCK_CLOEXEC, + }; + class shared_fd { int fd; std::atomic_int* guard; @@ -64,7 +91,7 @@ namespace gp{ , last_error(0) {} - shared_fd(shared_fd& oth) + shared_fd(const shared_fd& oth) : fd(oth.fd) , guard(oth.guard) , last_error(0) @@ -82,7 +109,7 @@ namespace gp{ oth.guard=nullptr; } - void operator=(shared_fd& oth) + void operator=(const shared_fd& oth) { this->~shared_fd(); fd = oth.fd; @@ -109,6 +136,29 @@ namespace gp{ return ret; } + static shared_fd net_socket(const net_socket_domain& dom, const net_socket_protocol& proto, net_socket_opt_flags& flags) + { + shared_fd ret{::socket((int)dom, (int)proto, (int)flags)}; + return ret; + } + + static shared_fd unix_socket(const net_socket_protocol& proto, const socket_opt_flags flags) { + shared_fd ret{::socket((int)AF_UNIX, (int)proto, (int)flags)}; + return ret; + } + + static std::pair unix_socketpair(const net_socket_protocol& proto, const socket_opt_flags flags) { + std::pair ret; + int fds[2]; + auto result = ::socketpair((int)AF_UNIX, (int)proto, (int)flags, fds); + if(result != 0) + return ret; + ret.first = shared_fd(fds[0]); + ret.second = shared_fd(fds[1]); + + return ret; + } + bool is_valid() const { return guard && (fd>=0); }