Browse Source

Add close functionality to Socket class (unix)

- add close functionality to Socket class for unix like systems
- extend tests for Socket class
Patrick-Christopher Mattulat 3 years ago
parent
commit
1e668dcd30

+ 1 - 0
include/ls_std/network/Socket.hpp

@@ -31,6 +31,7 @@ namespace ls_std {
       Socket();
       ~Socket() override = default;
 
+      bool close() const;
       bool create(ls_std::AddressFamily _addressFamily, ls_std::SocketType _socketType, ls_std::NetworkProtocol _networkProtocol);
 
     private:

+ 13 - 0
source/ls_std/network/Socket.cpp

@@ -12,6 +12,7 @@
 #if defined(unix) || defined(__APPLE__)
 #include <sys/socket.h>
 #include <resolv.h>
+#include <unistd.h>
 #endif
 #ifdef _WIN32
 #include <http.h>
@@ -20,6 +21,18 @@
 ls_std::Socket::Socket() : ls_std::Class("Socket")
 {}
 
+bool ls_std::Socket::close() const
+{
+  bool closed;
+
+  #if defined(unix) || defined(__APPLE__)
+    int result = ::close(this->descriptor);
+    closed = result == 0;
+  #endif
+
+  return closed;
+}
+
 bool ls_std::Socket::create(ls_std::AddressFamily _addressFamily, ls_std::SocketType _socketType, ls_std::NetworkProtocol _networkProtocol)
 {
   bool created;

+ 10 - 0
test/cases/network/SocketTest.cpp

@@ -21,6 +21,16 @@ namespace {
       void TearDown() override {}
   };
 
+  TEST_F(SocketTest, close)
+  {
+    ls_std::Socket socket {};
+    ASSERT_TRUE(socket.create(ls_std::ADDRESS_FAMILY_IP_V4, ls_std::SOCKET_TYPE_STREAM, ls_std::NETWORK_PROTOCOL_TCP_IP));
+    ASSERT_TRUE(socket.close());
+
+    ls_std::Socket anotherSocket {};
+    ASSERT_TRUE(anotherSocket.close());
+  }
+
   TEST_F(SocketTest, create)
   {
     ls_std::Socket socket {};