Browse Source

Unix and net sockets started

devel
Ludovic 'Archivist' Lagouardette 5 years ago
parent
commit
f0103d8284
1 changed files with 52 additions and 2 deletions
  1. +52
    -2
      include/shared_fd.hpp

+ 52
- 2
include/shared_fd.hpp View File

@ -3,6 +3,8 @@
#include <unistd.h> #include <unistd.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string> #include <string>
#include <atomic> #include <atomic>
#include <cassert> #include <cassert>
@ -47,6 +49,31 @@ namespace gp{
sticky_bit = S_ISVTX, 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 { class shared_fd {
int fd; int fd;
std::atomic_int* guard; std::atomic_int* guard;
@ -64,7 +91,7 @@ namespace gp{
, last_error(0) , last_error(0)
{} {}
shared_fd(shared_fd& oth)
shared_fd(k">const shared_fd& oth)
: fd(oth.fd) : fd(oth.fd)
, guard(oth.guard) , guard(oth.guard)
, last_error(0) , last_error(0)
@ -82,7 +109,7 @@ namespace gp{
oth.guard=nullptr; oth.guard=nullptr;
} }
void operator=(shared_fd& oth)
void operator=(k">const shared_fd& oth)
{ {
this->~shared_fd(); this->~shared_fd();
fd = oth.fd; fd = oth.fd;
@ -109,6 +136,29 @@ namespace gp{
return ret; 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<shared_fd,shared_fd> unix_socketpair(const net_socket_protocol& proto, const socket_opt_flags flags) {
std::pair<gp::shared_fd, gp::shared_fd> 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 { bool is_valid() const {
return guard && (fd>=0); return guard && (fd>=0);
} }

Loading…
Cancel
Save