From 7420a170928da75cb860e3fc8804416babdeec8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Smr=C5=BE?= Date: Sat, 12 Aug 2023 17:53:08 +0200 Subject: New class for network protocol implementation --- src/network/protocol.cpp | 69 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/network/protocol.cpp (limited to 'src/network/protocol.cpp') diff --git a/src/network/protocol.cpp b/src/network/protocol.cpp new file mode 100644 index 0000000..63cfde5 --- /dev/null +++ b/src/network/protocol.cpp @@ -0,0 +1,69 @@ +#include "protocol.h" + +#include +#include + +#include + +namespace erebos { + +NetworkProtocol::NetworkProtocol(): + sock(-1) +{} + +NetworkProtocol::NetworkProtocol(int s): + sock(s) +{} + +NetworkProtocol::NetworkProtocol(NetworkProtocol && other): + sock(other.sock) +{ + other.sock = -1; +} + +NetworkProtocol & NetworkProtocol::operator=(NetworkProtocol && other) +{ + sock = other.sock; + other.sock = -1; + return *this; +} + +NetworkProtocol::~NetworkProtocol() +{ + if (sock >= 0) + close(sock); +} + +bool NetworkProtocol::recvfrom(vector & buffer, sockaddr_in6 & addr) +{ + socklen_t addrlen = sizeof(addr); + buffer.resize(4096); + ssize_t ret = ::recvfrom(sock, buffer.data(), buffer.size(), 0, + (sockaddr *) &addr, &addrlen); + if (ret < 0) + throw std::system_error(errno, std::generic_category()); + if (ret == 0) + return false; + + buffer.resize(ret); + return true; +} + +void NetworkProtocol::sendto(const vector & buffer, sockaddr_in addr) +{ + ::sendto(sock, buffer.data(), buffer.size(), 0, + (sockaddr *) &addr, sizeof(addr)); +} + +void NetworkProtocol::sendto(const vector & buffer, sockaddr_in6 addr) +{ + ::sendto(sock, buffer.data(), buffer.size(), 0, + (sockaddr *) &addr, sizeof(addr)); +} + +void NetworkProtocol::shutdown() +{ + ::shutdown(sock, SHUT_RDWR); +} + +} -- cgit v1.2.3