Git Product home page Git Product logo

libsocket's Introduction

README for libsocket

Travis Build Status

Find the docs on GitHub pages

BUILDING libsocket

If you want to install both libsocket and libsocket++, simply use this command:

$ mkdir build && cd build
$ cmake ..
$ make # or make install

This installs the SOs libsocket.so and libsocket++.so to /usr/lib/ and the header files to /usr/include/libsocket. You may change these paths in the CMakeLists.txt file in the project root.

Note the changed library name on SunOS, where it is called libsocket_hl (for "high level").

CMake is required to support object libraries, which is the case in versions higher than or equal to 2.8.

WHAT IS libsocket AND WHY SHOULD I USE IT?

libsocket is a library with a C part and a C++ part making sockets usage easy and clean.

Using the C part:

  • Link against libsocket.so
  • Functions combining more than one operation on sockets (e.g. create and connect TCP socket)
  • Main principle: "One function to connect a socket, one to close it."

Using the C++ part:

  • Link against libsocket++.so
  • Classes representing the different socket types, e.g. TCP client sockets, UNIX DGRAM "server" sockets.
  • Complex (almost complicated...) class hierarchy (doc/libsocket++/classes.svg) reducing duplication.
  • C++ish implementation (features include overloaded stream (<<, >>) operators, functions accepting std::string objects and more-or-less STL use), so -> good integration in other applications or libraries.
  • Using C++11 features: The copy constructor of the socket base class is deleted; this enables the destructor to safely close the socket when it leaves the visible scope. Some functions are internally using unique_ptrs to enable safe deallocation.

FEATURES AND ADVANTAGES

The libsocket library has the following features:

  • IPv4 (client, server)
  • IPv6 (client, server; if your machine supports it)
  • TCP (client, server)
  • UDP (client, server -- the difference is that client sockets may be connected to an endpoint)
  • UNIX Domain Sockets (DGRAM/STREAM server/client)
  • IPv4/IPv6 multicast (only in C)
  • Abstraction classes for select(2) and epoll(7) (C++)
  • Easy use (one function call to get a socket up and running, another one to close it)
  • RAII, no-copy classes -- resource leaks are hard to do.
  • Proper error processing (using errno, gai_strerror() etc.) and C++ exceptions.

One of the main advantages of libsocket is that you don't have to write the complex and error-prone procedures for connecting a socket, checking it for errors etc. yourself. Your networked programs become shorter and better readable.

libsocket supports the important socket types: INET/INET6 with TCP and UDP; and UNIX DGRAM/STREAM.

Almost every function working with sockets is wrapped by libsocket, e.g.:

  • sendto
  • recvfrom
  • accept
  • socket/connect - one function
  • socket/bind - one function

libsocket is designed to not use a "proprietary" socket format (as libc does with its FILE type) giving you the possibility to operate on the raw file descriptor with functions other than those provided by libsocket.

PLATFORMS

Please let me know if a platform is not supported as well as it should, or if you managed to port libsocket to a new platform.

GNU/Linux

Libsocket works best on modern linux systems (sorry!). It needs a C++11 compiler like g++ or clang++. Override the default compiler using the flag -DCMAKE_CXX_COMPILER=<compiler> or -DCMAKE_C_COMPILER=<compiler>.

FreeBSD

Other than on Linux systems libsocket is known to work as well (although not really thoroughly tested) on FreeBSD systems with working C++11 stack. The library has been tested on a FreeBSD 10.0-RC4 amd64 system using the shipped compilers (which is clang 3.3).

SunOS: OpenIndiana, (Solaris?)

The library part written in C works (partly) also on OpenIndiana; this has been verified using SunOS openindiana 5.11 oi_151a8.

Because a modern C++ compiler was not available at the time of testing, the C++ library part is not built on SunOS systems.

Another hurdle is that Solaris already ships with a libsocket containing the standard socket functions. The C library is thus renamed to libsocket_hl on SunOS. You have to link your programs using the flag -lsocket_hl, not -lsocket.

SunOS limitations

  • The UDP server example (examples/echo_dgram_server.c) refuses to create a socket. The error is "Operation not supported on transport endpoint".
  • The TCP server example (examples/transmission_server.c) also fails when trying to create the socket. Here, the error displayed is "Invalid argument". I'm quite sure that these issues can be fixed with a little investigation and knowledge of SunOS.

OpenBSD

libsocket does not work on OpenBSD yet because there are some more fundamental source level incompatibilities than those between Linux and FreeBSD/OpenIndiana-SunOS.

Other OSs

If you're using libsocket successfully on other platforms (or even ported it), please let me know.

How to use libsocket: static vs. dynamic

Linking statically

It's possible to link libsocket statically into your program (by placing the .c[pp] and .h[pp] files in your source tree or linking against a .a file). You don't have to mind legal issues because libsocket is licensed by a slightly modified 2-clause BSD license which permits any use, as long as you include the license text in your product (so it's clear that libsocket is licensed by this License) and the notice that we wrote libsocket (as described in the license). It's ok to mention libsocket in your product's Readme or advertisements anyway.

Linking statically in CMake Projects

It is possible to produce static libraries for linking by setting the cmake configuration option BUILD_STATIC_LIBS=ON. This can be done from command line or in your CMakeLists.txt.

SET(BUILD_STATIC_LIBS ON) add_subdirectory(libsocket)

target_link_libraries(MyProject libsocket_int) # C linking
target_link_libraries(MyProject libsocket++_int) # C++ linking

Please note the cmake targets for static libraries are <libname>_int, but the produced libraries will have the expected libsocket(++).a name on disk.

Linking dynamically

The recommended method to use libsocket is to link your program against the libsocket SO (DLL). Using this method is quite easy; you have to compile the dynamic libraries (libsocket and libsocket++) using the Makefile (see section "BUILDING")

Linking your programs against the library is also simple: if $OBJECTS are your object files, then link them together using one of these commands:

    $ gcc -o yourprog -lsocket $OBJECTS
    # or for C++
    $ g++ -o yourprog -lsocket++ $OBJECTS

You only need to link against one library, even when using C++, because libsocket++ is already linked against libsocket.

If you distribute your program in binary form, it's possible to distribute the library binaries along with your program and install them along your program.

EXAMPLES

You may test libsocket and make some experiences by playing with the examples provided in the standard libsocket distribution in examples/ and examples++. More detailed descriptions can be found in the source files. The collection of examples contain (among others):

(C)

  • http.c: A simple http client
  • echo_dgram_server.c, echo_dgram_client.c, echo_dgram_connect_client.c: Shows how to use UDP sockets, both in connected and unconnected mode.
  • unix_stream_client.c, unix_stream_server.c: Demonstrating UNIX STREAM sockets as echo server/client
  • unix_dgram_client.c, unix_dgram_server.c: Demonstrating UNIX DGRAM sockets as simple server/client transmitting text.
  • multicast-listen.c: Demonstrating how to use libinetsocket for multicast networking.

Build these with gcc -o <outfile> -lsocket <example-name>.

(C++)

  • http.cpp, http_2.cpp: Two simple HTTP clients using slightly different approaches
  • server.cpp, client.cpp: TCP client and server
  • unix_client_dgram.cpp: Writes a message to the syslog using UNIX DGRAM sockets
  • echo_server.cpp, echo_client_conn.cpp, echo_client_sndto.cpp: UDP client/server (two clients: One using sendto(), another using connected datagram sockets)
  • unix_client_stream.cpp, unix_server_stream.cpp: Client/Server using UNIX STREAM sockets.

Build these with [clan]g++ -std=c++11 -lsocket++ -o <outfile> <example-name>.

You should have a look at the length of the code; while http.c is complete with 24 sloc (source lines of code) - the quite similar client simple-http (https://github.com/dermesser/Simple-HTTP-client) uses almost 70 lines of code.

TODO

  • Currently nothing! libsocket is not actively developed, as it is mostly feature complete, but it is actively maintained.

libsocket's People

Contributors

booto avatar brmateus2 avatar dermesser avatar dinarrow avatar dsorber avatar elfring avatar jaroslavrehorka avatar kamakado avatar mgruhler avatar mx avatar nick-piotrowski avatar novadan avatar offa avatar shelnutt2 avatar susumuo avatar thirtythreeforty avatar victorlamoine avatar whackashoe avatar william9523 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libsocket's Issues

FreeBSD - build failed

FreeBSD 12.1-RELEASE-p10
Clang 8.0.1 (from base)

Scanning dependencies of target socket_o
[  4%] Building C object C/CMakeFiles/socket_o.dir/inet/libinetsocket.c.o
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:11:9: warning: 'LIBSOCKET_LINUX' macro redefined [-Wmacro-redefined]
#define LIBSOCKET_LINUX 1
        ^
/home/peter/Programming/libsocket/build/headers/conf.h:2:9: note: previous definition is here
#define LIBSOCKET_LINUX 0
        ^
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:13:9: warning: 'LIBSOCKET_FREEBSD' macro redefined [-Wmacro-redefined]
#define LIBSOCKET_FREEBSD 0
        ^
/home/peter/Programming/libsocket/build/headers/conf.h:3:9: note: previous definition is here
#define LIBSOCKET_FREEBSD 1
        ^
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:467:20: warning: variable 'addrlen' is used uninitialized whenever 'if' condition is
      false [-Wsometimes-uninitialized]
        } else if (oldsockaddr.ss_family == AF_INET6) {
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:474:42: note: uninitialized use occurs here
            (he = gethostbyaddr(addrptr, addrlen, oldsockaddr.ss_family))) {
                                         ^~~~~~~
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:467:16: note: remove the 'if' if its condition is always true
        } else if (oldsockaddr.ss_family == AF_INET6) {
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:397:19: note: initialize the variable 'addrlen' to silence this warning
    size_t addrlen;
                  ^
                   = 0
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:504:21: warning: unused variable 'deconnect' [-Wunused-variable]
    struct sockaddr deconnect;
                    ^
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:868:20: warning: variable 'in_addrlen' is used uninitialized whenever 'if' condition
      is false [-Wsometimes-uninitialized]
        } else if (oldsockaddr.ss_family == AF_INET6) {
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:875:42: note: uninitialized use occurs here
            (he = gethostbyaddr(addrptr, in_addrlen, oldsockaddr.ss_family))) {
                                         ^~~~~~~~~~
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:868:16: note: remove the 'if' if its condition is always true
        } else if (oldsockaddr.ss_family == AF_INET6) {
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:807:22: note: initialize the variable 'in_addrlen' to silence this warning
    size_t in_addrlen;
                     ^
                      = 0
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:1021:43: error: no member named 'ifr_ifindex' in 'struct ifreq'
            mreq4.imr_ifindex = interface.ifr_ifindex;
                                ~~~~~~~~~ ^
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:1059:48: error: no member named 'ifr_ifindex' in 'struct ifreq'
            mreq6.ipv6mr_interface = interface.ifr_ifindex;
                                     ~~~~~~~~~ ^
/home/peter/Programming/libsocket/C/inet/libinetsocket.c:1062:61: error: use of undeclared identifier 'IPV6_ADD_MEMBERSHIP'
        if (-1 == check_error(setsockopt(sfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
                                                            ^
5 warnings and 3 errors generated.
*** Error code 1

Stop.
make[2]: stopped in /usr/home/peter/Programming/libsocket/build
*** Error code 1

Stop.
make[1]: stopped in /usr/home/peter/Programming/libsocket/build
*** Error code 1

Stop.
make: stopped in /usr/home/peter/Programming/libsocket/build

Unix Stream Socket Server

Hi,
firstly compliments for your library.
Now i use your library into a thread of my C++ program. I've a question.
This is my piece of code (server thread):

while (1){
memset(shared_in,0,3000);
try {
unix_stream_server srv(bindpath);
unique_ptr<unix_stream_client> client;
client = srv.accept2();
client->rcv(shared_in,3000);
*client << shared_out;
}catch (const libsocket::socket_exception& exc){
std::cerr << exc.mesg;
}
}

If i connect a client, but it for a problem close the connection before receiving the response from the server, my program exit (from all threads) when i call

*client << shared_out;

...where shared_out is a variable with the value passed from the second thread.
How can i solve?

Thanks a lot and Regards

"Address already in use" issue

I keep getting the "Address already in use" error when trying to create an inet stream server using an addr/port combination that has been previously used. Here are the steps to recreate the issue:
1: Create an inet_stream_server as described in server.cpp example using the SO_REUSEADDR flag.
2: Connect a client to the server.
3: Destroy the server (returns without errors)

Repeating step 1 using the same addr/port combination as prev. used causes the aforementioned error,

Any advice?

Thanks

compilation error

i use libsocket to compile another project but i have this error , what this is mean ?

/home/pi/libsocket/C++/streamclient.cpp:130: >>(std::string) input: Error while reading! (Connection reset by peer)
errno code: 104Socket client closed the connection

C++ style comments are not allowed in ISO C90

My project requires the older C90 standard. The // comments in libinetsocket.h are causing compile errors. There's only 2 of them in the file. It looks like an easy fix.

C++ style comments are not allowed in ISO C90

compile error

=== MAKE SURE YOU INSTALLED THE LATEST VERSION AS S/O! ===
Starting test suite examples/...
Testing HTTP client...
/tmp/ccFFSk2Z.o: In function `main':
http.c:(.text+0x37): undefined reference to `create_inet_stream_socket'
http.c:(.text+0x116): undefined reference to `shutdown_inet_stream_socket'
http.c:(.text+0x190): undefined reference to `destroy_inet_socket'
collect2: error: ld returned 1 exit status

os info:


 uname -a
Linux iZ25wcw25xrZ 3.13.0-32-generic #57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux


> g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.8/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.8.4-2ubuntu1~14.04.3' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libmudflap --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)


Upgrade cmake to 3.13+

There's a warning when configure using cmake 3.16

Policy CMP0077 is not set: option() honors normal variables. 

Improvements with move assignments?

The current standard for the programming language "C++" provides several features which needed some time to become available in corresponding compilers. Software developers needed also some time to become used to them. One of them is the handling of move assignments.

Moving contents from objects instead of copying them completely can result in improvements for the execution speed. I am curious if an approach like the following helps in this direction.

diff --git a/C++/inetserverstream.cpp b/C++/inetserverstream.cpp
index ec45817..8dff5d4 100644
--- a/C++/inetserverstream.cpp
+++ b/C++/inetserverstream.cpp
@@ -1,6 +1,7 @@
 # include <string.h>
 # include <string>
 # include <memory>
+# include <utility>


 /*
@@ -183,8 +184,8 @@ namespace libsocket
        }

        client->sfd = client_sfd;
-       client->host = string(src_host.get()); // these strings are destructed automatically when the returned object is deleted. (http://stackoverflow.com/a/6256543)
-       client->port = string(src_port.get()); //
+       client->host = std::move( decltype(client->host) (src_host.get()) );
+       client->port = std::move( decltype(client->port) (src_port.get()) );
        client->proto = proto;

        return client;

Build on old systems (e.g., Ubuntu 12.04)

I use an old system with cmake 2.8.7 (not support TARGET_OBJECTS) and gcc 4.6.3 (not support -std=c++11) so the build does not work. The following patch helps me build successfully.

Hope that helps.

diff --git a/C++/CMakeLists.txt b/C++/CMakeLists.txt
index 36121c5..d05f845 100644
--- a/C++/CMakeLists.txt
+++ b/C++/CMakeLists.txt
@@ -1,6 +1,6 @@
 cmake_minimum_required(VERSION 2.8)

-SET(CMAKE_CXX_FLAGS "-std=c++11") # -DVERBOSE")
+SET(CMAKE_CXX_FLAGS "-std=c++0x") # -DVERBOSE")

 ADD_DEFINITIONS("-DMIXED")

diff --git a/C/CMakeLists.txt b/C/CMakeLists.txt
index 881c5c2..7d7b17d 100644
--- a/C/CMakeLists.txt
+++ b/C/CMakeLists.txt
@@ -7,10 +7,12 @@ SET(libsocket_src

 IF ( NOT IS_SUNOS )
     ADD_DEFINITIONS(-fPIC) # for the static library which needs to be linked into the shared libsocket++.so object.
-    ADD_LIBRARY(socket_o OBJECT ${libsocket_src})
+    #ADD_LIBRARY(socket_o OBJECT ${libsocket_src})

-    ADD_LIBRARY(socket MODULE $<TARGET_OBJECTS:socket_o>)
-    ADD_LIBRARY(socket_int STATIC $<TARGET_OBJECTS:socket_o>)
+    #ADD_LIBRARY(socket MODULE $<TARGET_OBJECTS:socket_o>)
+    #ADD_LIBRARY(socket_int STATIC $<TARGET_OBJECTS:socket_o>)
+    ADD_LIBRARY(socket MODULE ${libsocket_src})
+    ADD_LIBRARY(socket_int STATIC ${libsocket_src})

     INSTALL(TARGETS socket DESTINATION ${LIB_DIR})
 ELSE() # On SunOS (e.g. OpenIndiana) we have to link against the system's libsocket. The library is renamed to libsocket_hl (hl = high-level)
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5233618..0def475 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -22,7 +22,7 @@ CONFIGURE_FILE(headers/conf.h.in ${CMAKE_SOURCE_DIR}/headers/conf.h)

 # Compiler configuration
 INCLUDE_DIRECTORIES(BEFORE ${CMAKE_SOURCE_DIR}/headers/)
-SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
 ADD_DEFINITIONS(-Wall -Wextra)
 #ADD_DEFINITIONS(-DVERBOSE)

libsocket::unix_dgram_client would unlink the socket's path

the unix_dgram_client's constructor, which contain the unix socket path, would unlink the socket path. The path cretate by unix server. The unix path would be no useful for server, after create the unix client.

unix_dgram_client(const char* path, int flags = 0) ==> create_unix_dgram_socket() ==> unlink(bind_path)

Error while Linking on Ubuntu 14.04

On my Ubuntu 14.04 I have installed this libaray without errors or warnings.
in /urs/lib/ is the libsocket++.so file. But when I execute the test.sh in the examples++ directory, I get erros, like undefined relation on libsocket::unix_stream_server::unix_stream_server(std::string const&, int) or something like that. It seems that these funktions are not implementet in the libsecket++.so file.

Alpine Linux build errors

Hello, I was trying to build libsocket in an Alpine Linux based Docker container and came across two errors. The errors occur at the same time and in the same file, but I've separated them for clarity.

Error 1:

In file included from /workspace/libsocket/headers/streamclient.hpp:5,
                 from /workspace/libsocket/C++/streamclient.cpp:48:
/workspace/libsocket/headers/socket.hpp:92:22: error: 'socklen_t' has not been declared
   92 |                      socklen_t optlen) const;
      |                      ^~~~~~~~~
make[2]: *** [C++/CMakeFiles/socket++_o.dir/build.make:154: C++/CMakeFiles/socket++_o.dir/streamclient.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:268: C++/CMakeFiles/socket++_o.dir/all] Error 2
make: *** [Makefile:152: all] Error 2

I think the reason for this error is because of where and how the definition for
socklen_t can be acquired on Alpine versus, for example, Ubuntu 18.04.

On Ubuntu 18.04 when compiling streamclient.cpp, the definition for
socklen_t is acquired by including <unistd.h> on line 37. This puts the
definition into the global scope, granting visibility of socklen_t to the
contents of the "socket.hpp" include, and therefore resulting in a successful compliation.

On Alpine, it seems like the primary way to get socklen_t is by including <sys/socket.h>,
which includes <bits/alltypes.h> in the following manner:

// Alpine <sys/socket.h>
// ...

#define __NEED_socklen_t

// ...

#include <bits/alltypes.h>

// ...

Satisfying the following definition in <bits/alltypes.h>:

// Alpine <bits/alltypes.h>
// ...

#if defined(__NEED_socklen_t) && !defined(__DEFINED_socklen_t)
typedef unsigned socklen_t;
#define __DEFINED_socklen_t
#endif

// ...

The header <unistd.h> also includes <bits/alltypes.h>, but the explicit
requirement of the __NEED_socklen_t definition on Alpine breaks
the manner in which the streamclient.cpp file acquires the globally scoped
definition of socklen_t.


Error 2:

In file included from /usr/include/fortify/sys/socket.h:22,
                 from /workspace/libsocket/C++/streamclient.cpp:42:
/workspace/libsocket/C++/streamclient.cpp: In member function 'void libsocket::stream_client_socket::shutdown(int)':
/workspace/libsocket/C++/streamclient.cpp:290:21: error: expected unqualified-id before numeric constant
  290 |     using BERKELEY::SHUT_RD;
      |                     ^~~~~~~
/workspace/libsocket/C++/streamclient.cpp:290:21: error: expected ';' before numeric constant
  290 |     using BERKELEY::SHUT_RD;
      |                     ^
      |                     ;
In file included from /usr/include/fortify/sys/socket.h:22,
                 from /workspace/libsocket/C++/streamclient.cpp:42:
/workspace/libsocket/C++/streamclient.cpp:291:21: error: expected unqualified-id before numeric constant
  291 |     using BERKELEY::SHUT_RDWR;
      |                     ^~~~~~~~~
/workspace/libsocket/C++/streamclient.cpp:291:21: error: expected ';' before numeric constant
  291 |     using BERKELEY::SHUT_RDWR;
      |                     ^
      |                     ;
In file included from /usr/include/fortify/sys/socket.h:22,
                 from /workspace/libsocket/C++/streamclient.cpp:42:
/workspace/libsocket/C++/streamclient.cpp:292:21: error: expected unqualified-id before numeric constant
  292 |     using BERKELEY::SHUT_WR;
      |                     ^~~~~~~
/workspace/libsocket/C++/streamclient.cpp:292:21: error: expected ';' before numeric constant
  292 |     using BERKELEY::SHUT_WR;
      |                     ^
      |                     ;
make[2]: *** [C++/CMakeFiles/socket++_o.dir/build.make:154: C++/CMakeFiles/socket++_o.dir/streamclient
.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:268: C++/CMakeFiles/socket++_o.dir/all] Error 2
make: *** [Makefile:152: all] Error 2

I think the reason for these errors is because SHUT_RD, SHUT_WR, and
SHUT_RDWR are only #defined in the header <sys/socket.h> on Alpine:

// Alpine <sys/sock.h>:
// ...

#define SHUT_RD 0
#define SHUT_WR 1
#define SHUT_RDWR 2

// ...

While on Ubuntu 18.04, for example, the header <sys/socket.h> is as follows:

// Ubuntu 18.04 <sys/sock.h>:
// ...

enum
{
  SHUT_RD = 0,		/* No more receptions.  */
#define SHUT_RD		SHUT_RD
  SHUT_WR,		/* No more transmissions.  */
#define SHUT_WR		SHUT_WR
  SHUT_RDWR		/* No more receptions or transmissions.  */
#define SHUT_RDWR	SHUT_RDWR
};

// ...

Thus, wrapping the #include <sys/socket.h> in the BERKELEY namespace in
streamclient.cpp on line 42-44 and the subsequent using directives at the
lines seen in the error message will break on Alpine Linux due to
the nonexistance of the enum.


Reproduction steps:
Build the following Docker image:

FROM alpine:3.11

RUN apk update && \
    apk upgrade && \
    apk add git bash wget curl cmake make && \
    apk add build-base

WORKDIR /workspace

RUN git clone https://github.com/dermesser/libsocket.git && \
    cd libsocket && \
    mkdir build && \
    cd build && \
    cmake .. -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ && \
    make

client from other languages

Is there any way that we can get a client from other languages, python or javascript on the echo server example, I tried on both in different ways but none of them are working.

Cannot connect to server when no DNS available

I encountered the following error on inet_stream_server side when I use inet_stream to connect to it with the server's IP address specified (VERBOSE set to 1)

Temporary failure in name resolution
/home/libsocket-2.4.1/C++/inetserverstream.cpp:169: inet_stream_server::accept() - could not accept new connection on stream server socket! (Success)

The reason is the getnameinfo fails when my system does not connect to the Internet. The /etc/resolv.conf on both client and server is
nameserver 127.0.0.1

I suggest to handle the case like following. (The patch has not been designed to work when _TRADITIONAL_RDNS is set, though)

diff --git a/C/inet/libinetsocket.c b/C/inet/libinetsocket.c
index 3dbb253..5b0208d 100644
--- a/C/inet/libinetsocket.c
+++ b/C/inet/libinetsocket.c
@@ -774,10 +774,12 @@ int accept_inet_stream_socket(int sfd, char* src_host, size_t src_host_len, char
           errstr = gai_strerror(retval);
           debug_write(errstr);
 # endif
-           return -1;
+      /* It is not a fatal error when the DNS is unavailable */
+      if (errno != 0)
+        return -1;
        }
 # endif

terminate called after throwing an instance of 'char const*'

In the examples++/http_examples folder, using modified build.sh of:

#!/bin/bash
g++ -o http http.cpp -lsocket++
g++ -o http_2 http_2.cpp -lsocket++
g++ -o http_epoll http_epoll.cpp -lsocket++

everything compiles with no warnings or errors. The http and http_2 programs run fine. However, the http_epoll application runs and terminates with the following output:

$ ./http_epoll
terminate called after throwing an instance of 'char const*'
Aborted

Test environment:

$ g++ --version
g++ (Ubuntu 9.4.0-1ubuntu1~16.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ uname -a
Linux asusubuntu16 4.15.0-142-generic #146~16.04.1-Ubuntu SMP Tue Apr 13 09:27:15 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

I tried compiling with g++ v5 but got the same result.

-O3 level optimization causes selectset.wait(n) to malfunction

I'm using libsocket++ for a project and I noticed that when compiling my code with GCC's "-O3" optimization level selectset.wait(n), where n > 0, returns immediately even though both the read and write ready lists are empty. When n=0 wait() behaves as expected. When compiling with -O2 (or lower) and setting n > 0 wait() also behaves as expected.

I did a little digging and the problem appears to be caused by this, from select.hpp:

    template<typename SockT>
    typename selectset<SockT>::ready_socks selectset<SockT>::wait(long long microsecs)
    {
    int n = 0;

    struct timeval *timeout = NULL;

    if ( microsecs != 0 )
    {
            struct timeval _timeout;
        timeout = &_timeout;

        long long micropart = microsecs % 1000000;
        long long secpart   = (microsecs - micropart) / 1000000;

        _timeout.tv_sec  = secpart;
        _timeout.tv_usec = microsecs;
    }

    n = select(highestfd(filedescriptors)+1,&readset,&writeset,NULL,timeout);

The struct timeval _timeout is declared inside the if block so it is scoped to that block. Therefore I'm guessing that GCC's -O3 optimizations detect this strip out that entire if block. The fix is trivial, of course, just move that declaration up outside of the if block. I tried out the fix on my local copy and wait() now works correctly when compiled with -O3 and n > 0.

My system is running Ubuntu 14.04.5 with GCC 4.8.4

Clarification for header file references

I am trying to achieve something with a few CMake scripts. Unfortunately, I stumble on a message like the following.

...
[ 67%] Building C object examples/CMakeFiles/get_address_family_c.dir/get_address_family.c.o
...
/home/elfring/Projekte/libsocket/lokal/examples/get_address_family.c:3:38: fatal error: libsocket/libinetsocket.h: No such file or directory
compilation terminated.
...

Other demonstration source files refer to a different header directory. How do you think about to change these references in the way that they can be resolved without the specification of a subdirectory there?
(The build system can provide appropriate include parameters if the file names are consistent, can't it?)

Calling setsockopts on unconnected socket

As far as I can tell, it isn't possible to set options on a socket without first getting it into the connected state. It would be useful to do this, for example, to set the socket option SO_REUSEADDR before connecting. The problem is that the socket isn't actually created until connection time.

Using setsockopt with inet_stream::getfd works fine after connecting, because the socket file descriptor is then valid.

Am I missing something, or is this not possible?

FreeBSD compilation fail

Hi,
uname -a
FreeBSD freebsd1 10.2-RELEASE-p9 FreeBSD 10.2-RELEASE-p9 #0: Thu Jan 14 01:32:46 UTC 2016 [email protected]:/usr/obj/usr/src/sys/GENERIC amd64
compiler
clang 3.4.1

The problem while compiling:

/home/alex/Downloads/libsocket-master/C/inet/libinetsocket.c:957:43: error: no member named 'ifr_ifindex' in 'struct ifreq'
mreq4.imr_ifindex = interface.ifr_ifindex;
~~~~~~~~~ ^
/home/alex/Downloads/libsocket-master/C/inet/libinetsocket.c:997:48: error: no member named 'ifr_ifindex' in 'struct ifreq'
mreq6.ipv6mr_interface = interface.ifr_ifindex;
~~~~~~~~~ ^
/home/alex/Downloads/libsocket-master/C/inet/libinetsocket.c:1000:60: error: use of undeclared identifier 'IPV6_ADD_MEMBERSHIP'
if ( -1 == check_error(setsockopt(sfd,IPPROTO_IPV6,IPV6_ADD_MEMBERSHIP,&mreq6,sizeof(struct ipv6_mreq))) )

Temporary solution:
Add to ./C/inet/libnetsocket.c:

#ifdef __FreeBSD__
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#define IPV6_DROP_MEMBERSHIP    IPV6_LEAVE_GROUP
#endif

Modify line ~960

# ifdef __FreeBSD__
    mreq4.imr_ifindex = interface.ifr_ifru.ifru_index;
#else       
    mreq4.imr_ifindex = interface.ifr_ifindex;
# endif

And modify line ~1005

# ifdef __FreeBSD__
        mreq6.ipv6mr_interface = interface.ifr_ifru.ifru_index;
#else       
        mreq6.ipv6mr_interface = interface.ifr_ifindex;
# endif

Modified file:
libinetsocket.c.tar.gz
I have attached the modified file.
Thanks.

problem installing library on ubuntu

Hello,

Thank you for the library, I have a problem installing it on ubuntu 12.04.
I have tried just to follow steps described at the top of README, but cmake CMakeLists.txt gives the following errors:

CMake Error at C/CMakeLists.txt:16 (ADD_LIBRARY):
Cannot find source file:

$<TARGET_OBJECTS:socket_o>

CMake Error in C/CMakeLists.txt:
Cannot find source file:

OBJECT

The problem with those errors and documentation, the documentation does not tell me what I should put for those variables and it is clear from the cmake errors those variables are not set.

Please let me know if I have overlooked something or if it is something that needs to be fixed.

Best,
Rovshen
MS CS
Baylor U

"Abstract socket namespace" support?

Libunixsocket does not currently support the "abstract socket namespace" feature of Linux. unix(7) says this about the ASN:

abstract: an abstract socket address is distinguished by the fact that sun_path[0] is a null byte ('\0').  The socket's address in this namespace is given by the additional bytes in sun_path that are covered by
      the  specified length of the address structure.  (Null bytes in the name have no special significance.)  The name has no connection with filesystem pathnames.  When the address of an abstract socket is returned
      by getsockname(2), getpeername(2), and accept(2), the returned addrlen is greater than sizeof(sa_family_t) (i.e., greater than 2), and the name of the socket is contained in the first (addrlen -  sizeof(sa_fam‐
      ily_t)) bytes of sun_path.  The abstract socket namespace is a nonportable Linux extension.

The reason of the lack of support for this feature is that the functions creating UNIX sockets are using strlen and strncpy for string handling, and those do not work with strings whose first byte is 0.

bug for epollset

in the epollset constructor, it create the epollfd.
epollfd = epoll_create1(0);
but in the destructor, it don't close it.
template

epollset<SocketT>::~epollset(void) {
    close(epollfd);  /* add close the epollfd */
    delete[] events;
}

Can this lib use in iOS?

Hi ,
Thank for this great job.I'am new to C++,I want to use this lib in iOS project,I wonder if it support?

Regards
Vienta

Possible memory leak on failed inet stream socket connections

When creating a inet stream socket using create_inet_stream_socket function, the hostname is resolved using getaddrinfo. On success this call returns a result list of possible endpoints that is only freed when a connection was successfully established.
But if the connection was not possible, the list is never freed because the function leaves returning -1 without cleaning up.

Cross-compiling discussion

I'm trying to cross compile this lib to run on multiple architecture like MIPS and ARM. If you guys have any decent suggestions, please discuss here.

Getting basic UDP example working?

Hi,
Not really an issue but I am a newbie c++ programmer trying to get a very basic UDP communication example working. I am running echo_server.cpp on 1 computer and echo_client_conn.cpp on another computer. I am getting

input: Error while reading! (Connection refused)

when I run the client program. The server program doesn't seem to be giving error. Can you help me diagnose what is the issue? I did not change anything besides the host value. Also ping to the server from client works. Thanks!

# include <iostream>
# include "../headers/inetserverdgram.hpp"
# include "../headers/exception.hpp"
# include <cstring>

// Server for echo_client_*.cpp
// simply receives a message and sends an answer.

int main(void)
{
    using std::string;

    string host = "192.168.0.111"; //ip address of server computer
    string port = "1234";

    string answer("Hello back from the server!");
    string from;
    string fromport;
    string buf;

    buf.resize(32);

    try {
	libsocket::inet_dgram_server srv(host,port,LIBSOCKET_BOTH);

	for (;;)
	{
	    srv.rcvfrom(buf,from,fromport);

	    std::cout << "Datagram from " << from << ":" << fromport << " " << buf << std::endl;

	    srv.sndto(answer,from,fromport);
	}

	srv.destroy();
    } catch (const libsocket::socket_exception& exc)
    {
	std::cerr << exc.mesg;
    }


    return 0;
}
client code
# include <iostream>
# include <unistd.h>
# include "../headers/inetclientdgram.hpp"
# include "../headers/exception.hpp"

/*
 * Sends and receives messages via connected UDP sockets
 */

int main(void)
{
    using std::string;

    string host = "192.168.0.111";//also put address of server here?
    string port = "1234";

    string answer;

    answer.resize(32);

    libsocket::inet_dgram_client sock(LIBSOCKET_IPv4);

    try {
	std::cout << sock.gethost();
    } catch (const libsocket::socket_exception& exc)
    {
	std::cerr << exc.mesg;
    }

    try {
	for ( int i = 0; i < 20; i++ )
	{
	    sock.connect(host,port);

	    sock << "Hello, server";

	    sock >> answer;

	    std::cout << "Answer from server: " << answer << std::endl;

	    sock.deconnect();
	}
    } catch ( const libsocket::socket_exception& exc )
    {
	std::cerr << exc.mesg;
    }

    sock.destroy();

    return 0;
}

Address already in use on a clean close

Hi, first thank you for the excellent libsocket library.

I have a problem similar to #61 in that TCP listen sockets on a server are kept in a TIME_WAIT state by linux (centos 7) for approximately 30 seconds. I've read #61 and tried the following but it didn't help:

sysctl net.ipv4.tcp_fin_timeout=5
sysctl net.ipv4.tcp_tw_recycle=1
sysctl net.ipv4.tcp_tw_reuse=1

I think I'm closing the listen stream & socket correctly:

listenStream->shutdown(LIBSOCKET_READ | LIBSOCKET_WRITE);
listenStream->destroy();
...
listenSocket.destroy();

Do you have any advice on how to combat this?

Add errno value to exceptions

errno value could be added to exceptions to simplify error handling. Until this is implemented, is it safe to assume that errno after calling a libsocket(++) function is the same that it would be after calling the corresponding low-level function?

Version check command

Which one is the stable version released for this and do we have any way to check the version number?

Regards,

Macro names are prone to collisions

Using single words as macro names can lead to obscure compilation errors. For example, the ev namespace in libev C++ library has constants named READ and WRITE. Defining macros with the same names makes these constants inaccessible.
libev has a C library too and there the ev::READ constant is called EV_READ. A similar emulation of namespaces is probably needed for libsocket.

Some macro names from libsocket code: READ, WRITE, TCP, UDP, STREAM, VERBOSE, BACKLOG, BOTH, NUMERIC.

Detect/check if inet_stream is closed

I want to be notified or at least check periodically if a libsocket::inet_stream created by a libsocket::inet_stream_server::accept() is closed.
I tried fcntl but it does not seem to work.

int r;
r = fcntl(cli_sock->getfd(), F_GETFL);
if (r == -1)
    is_ok = false;

memory leakage in create_unix_stream_socket

After check the connection status in below code, the sfd variable needs to be freed.
if ( -1 == check_error(connect(sfd,(struct sockaddr*)&saddr,sizeof(saddr.sun_family) + strlen(saddr.sun_path)) ) ) return -1;

The code should be changed as below.

if ( -1 == check_error(connect(sfd,(struct sockaddr*)&saddr,sizeof(saddr.sun_family) + strlen(saddr.sun_path)) ) ) { close(sfd); return -1; }

Compile libsocket on windows for arm

I use a cross compiler to compile my code on my windows machine for the arm-none-linux-gnueabi.
I would like to know how I can compile libsocket in this case.
Cmake does not seem to be happy with my crosscompiler.
Also some headers like sys/socket.h are not available. Any ideas?

websockets

(noob alert)

Is it possible to create websockets? And if not, what has to be done to make that possible?

Errors compiling using build.sh in folder examples++

Creates the following problems with gcc v9:

./build.sh
/tmp/ccpXA2pb.o: In function run_client()': dgram_over_stream.cpp:(.text+0x266): undefined reference to libsocket::inet_stream::inet_stream(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int, int)'
dgram_over_stream.cpp:(.text+0x27e): undefined reference to libsocket::socket::socket(libsocket::socket&&)' dgram_over_stream.cpp:(.text+0x2a6): undefined reference to libsocket::dgram_over_stream::dgram_over_stream(libsocket::stream_client_socket)'
dgram_over_stream.cpp:(.text+0x2c1): undefined reference to libsocket::socket::~socket()' dgram_over_stream.cpp:(.text+0x2d8): undefined reference to libsocket::dgram_over_stream::sndmsg(void const*, unsigned long)'
dgram_over_stream.cpp:(.text+0x301): undefined reference to libsocket::dgram_over_stream::rcvmsg(void*, unsigned long)' dgram_over_stream.cpp:(.text+0x408): undefined reference to libsocket::socket::~socket()'
/tmp/ccpXA2pb.o: In function run_string_client()': dgram_over_stream.cpp:(.text+0x4b6): undefined reference to libsocket::inet_stream::inet_stream(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int, int)'
dgram_over_stream.cpp:(.text+0x4d4): undefined reference to libsocket::socket::socket(libsocket::socket&&)' dgram_over_stream.cpp:(.text+0x4fc): undefined reference to libsocket::dgram_over_stream::dgram_over_stream(libsocket::stream_client_socket)'
dgram_over_stream.cpp:(.text+0x51c): undefined reference to libsocket::socket::~socket()' dgram_over_stream.cpp:(.text+0x57a): undefined reference to libsocket::dgram_over_stream::sndmsg(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&)'
dgram_over_stream.cpp:(.text+0x5af): undefined reference to libsocket::dgram_over_stream::rcvmsg(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*)' dgram_over_stream.cpp:(.text+0x69d): undefined reference to libsocket::socket::~socket()'
/tmp/ccpXA2pb.o: In function run_server()': dgram_over_stream.cpp:(.text+0x76a): undefined reference to libsocket::inet_stream_server::inet_stream_server(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int, int)'
dgram_over_stream.cpp:(.text+0x77d): undefined reference to libsocket::inet_stream_server::accept(int, int)' dgram_over_stream.cpp:(.text+0x794): undefined reference to libsocket::socket::socket(libsocket::socket&&)'
dgram_over_stream.cpp:(.text+0x7bc): undefined reference to libsocket::dgram_over_stream::dgram_over_stream(libsocket::stream_client_socket)' dgram_over_stream.cpp:(.text+0x7d7): undefined reference to libsocket::socket::~socket()'
dgram_over_stream.cpp:(.text+0x800): undefined reference to libsocket::dgram_over_stream::rcvmsg(void*, unsigned long)' dgram_over_stream.cpp:(.text+0x8ba): undefined reference to libsocket::dgram_over_stream::sndmsg(void const*, unsigned long)'
/tmp/ccpXA2pb.o: In function run_vec_client()': dgram_over_stream.cpp:(.text+0x974): undefined reference to libsocket::inet_stream::inet_stream(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int, int)'
dgram_over_stream.cpp:(.text+0x992): undefined reference to libsocket::socket::socket(libsocket::socket&&)' dgram_over_stream.cpp:(.text+0x9bd): undefined reference to libsocket::dgram_over_stream::dgram_over_stream(libsocket::stream_client_socket)'
dgram_over_stream.cpp:(.text+0x9d9): undefined reference to libsocket::socket::~socket()' dgram_over_stream.cpp:(.text+0xa31): undefined reference to libsocket::dgram_over_stream::sndmsg(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&)'
dgram_over_stream.cpp:(.text+0xa66): undefined reference to libsocket::dgram_over_stream::rcvmsg(std::vector<unsigned char, std::allocator<unsigned char> >*)' dgram_over_stream.cpp:(.text+0xb76): undefined reference to libsocket::socket::~socket()'
/tmp/ccpXA2pb.o: In function libsocket::stream_client_socket::~stream_client_socket()': dgram_over_stream.cpp:(.text._ZN9libsocket20stream_client_socketD1Ev[_ZN9libsocket20stream_client_socketD1Ev]+0x13): undefined reference to libsocket::socket::~socket()'
/tmp/ccpXA2pb.o: In function virtual thunk to libsocket::stream_client_socket::~stream_client_socket()': dgram_over_stream.cpp:(.text._ZN9libsocket20stream_client_socketD1Ev[_ZN9libsocket20stream_client_socketD1Ev]+0x3a): undefined reference to libsocket::socket::~socket()'
/tmp/ccpXA2pb.o: In function libsocket::stream_client_socket::~stream_client_socket()': dgram_over_stream.cpp:(.text._ZN9libsocket20stream_client_socketD0Ev[_ZN9libsocket20stream_client_socketD0Ev]+0x18): undefined reference to libsocket::socket::~socket()'
/tmp/ccpXA2pb.o: In function virtual thunk to libsocket::stream_client_socket::~stream_client_socket()': dgram_over_stream.cpp:(.text._ZN9libsocket20stream_client_socketD0Ev[_ZN9libsocket20stream_client_socketD0Ev]+0x4e): undefined reference to libsocket::socket::~socket()'
/tmp/ccpXA2pb.o:dgram_over_stream.cpp:(.text._ZN9libsocket11inet_streamD0Ev[_ZN9libsocket11inet_streamD0Ev]+0x4e): more undefined references to libsocket::socket::~socket()' follow /tmp/ccpXA2pb.o:(.rodata._ZTIN9libsocket20stream_client_socketE[_ZTIN9libsocket20stream_client_socketE]+0x18): undefined reference to typeinfo for libsocket::socket'
/tmp/ccpXA2pb.o:(.rodata._ZTIN9libsocket11inet_socketE[_ZTIN9libsocket11inet_socketE]+0x18): undefined reference to typeinfo for libsocket::socket' /tmp/ccpXA2pb.o:(.rodata._ZTVN9libsocket20stream_client_socketE[_ZTVN9libsocket20stream_client_socketE]+0x58): undefined reference to libsocket::socket::destroy()'
/tmp/ccpXA2pb.o:(.rodata._ZTCN9libsocket11inet_streamE80_NS_20stream_client_socketE[_ZTVN9libsocket11inet_streamE]+0x58): undefined reference to libsocket::socket::destroy()' /tmp/ccpXA2pb.o:(.rodata._ZTCN9libsocket11inet_streamE0_NS_11inet_socketE[_ZTVN9libsocket11inet_streamE]+0x58): undefined reference to libsocket::socket::destroy()'
/tmp/ccpXA2pb.o:(.rodata._ZTVN9libsocket11inet_streamE[_ZTVN9libsocket11inet_streamE]+0x80): undefined reference to libsocket::socket::destroy()' /tmp/ccpXA2pb.o:(.rodata._ZTCN9libsocket18inet_stream_serverE0_NS_11inet_socketE[_ZTVN9libsocket18inet_stream_serverE]+0x58): undefined reference to libsocket::socket::destroy()'
/tmp/ccpXA2pb.o:(.rodata._ZTVN9libsocket18inet_stream_serverE[_ZTVN9libsocket18inet_stream_serverE]+0x58): more undefined references to libsocket::socket::destroy()' follow collect2: error: ld returned 1 exit status /tmp/cc3potW2.o: In function main':
framing.cpp:(.text.startup+0x2b): undefined reference to libsocket::encode_uint32(unsigned int, char*)' framing.cpp:(.text.startup+0x35): undefined reference to libsocket::decode_uint32(char const*)'
collect2: error: ld returned 1 exit status
/tmp/ccUUZQym.o: In function libsocket::unix_dgram_client::~unix_dgram_client()': unix_dgram_syslogclient.cpp:(.text._ZN9libsocket17unix_dgram_clientD1Ev[_ZN9libsocket17unix_dgram_clientD1Ev]+0x37): undefined reference to libsocket::socket::~socket()'
/tmp/ccUUZQym.o: In function non-virtual thunk to libsocket::unix_dgram_client::~unix_dgram_client()': unix_dgram_syslogclient.cpp:(.text._ZN9libsocket17unix_dgram_clientD1Ev[_ZN9libsocket17unix_dgram_clientD1Ev]+0x77): undefined reference to libsocket::socket::~socket()'
/tmp/ccUUZQym.o: In function virtual thunk to libsocket::unix_dgram_client::~unix_dgram_client()': unix_dgram_syslogclient.cpp:(.text._ZN9libsocket17unix_dgram_clientD1Ev[_ZN9libsocket17unix_dgram_clientD1Ev]+0xbe): undefined reference to libsocket::socket::~socket()'
/tmp/ccUUZQym.o: In function non-virtual thunk to libsocket::unix_dgram_client::~unix_dgram_client()': unix_dgram_syslogclient.cpp:(.text._ZN9libsocket17unix_dgram_clientD0Ev[_ZN9libsocket17unix_dgram_clientD0Ev]+0x40): undefined reference to libsocket::socket::~socket()'
/tmp/ccUUZQym.o: In function virtual thunk to libsocket::unix_dgram_client::~unix_dgram_client()': unix_dgram_syslogclient.cpp:(.text._ZN9libsocket17unix_dgram_clientD0Ev[_ZN9libsocket17unix_dgram_clientD0Ev]+0xa2): undefined reference to libsocket::socket::~socket()'
/tmp/ccUUZQym.o:unix_dgram_syslogclient.cpp:(.text._ZN9libsocket17unix_dgram_clientD0Ev[_ZN9libsocket17unix_dgram_clientD0Ev]+0xfb): more undefined references to libsocket::socket::~socket()' follow /tmp/ccUUZQym.o: In function main':
unix_dgram_syslogclient.cpp:(.text.startup+0x61): undefined reference to libsocket::unix_dgram_client::unix_dgram_client(int)' unix_dgram_syslogclient.cpp:(.text.startup+0x75): undefined reference to libsocket::unix_dgram::sndto(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int)'
unix_dgram_syslogclient.cpp:(.text.startup+0x7f): undefined reference to libsocket::socket::destroy()' /tmp/ccUUZQym.o:(.rodata._ZTIN9libsocket19dgram_client_socketE[_ZTIN9libsocket19dgram_client_socketE]+0x18): undefined reference to typeinfo for libsocket::socket'
/tmp/ccUUZQym.o:(.rodata._ZTIN9libsocket11unix_socketE[_ZTIN9libsocket11unix_socketE]+0x18): undefined reference to typeinfo for libsocket::socket' /tmp/ccUUZQym.o:(.rodata._ZTCN9libsocket17unix_dgram_clientE40_NS_19dgram_client_socketE[_ZTVN9libsocket17unix_dgram_clientE]+0x58): undefined reference to libsocket::socket::destroy()'
/tmp/ccUUZQym.o:(.rodata._ZTCN9libsocket17unix_dgram_clientE0_NS_11unix_socketE[_ZTVN9libsocket17unix_dgram_clientE]+0x58): undefined reference to libsocket::socket::destroy()' /tmp/ccUUZQym.o:(.rodata._ZTCN9libsocket17unix_dgram_clientE0_NS_10unix_dgramE[_ZTVN9libsocket17unix_dgram_clientE]+0x58): undefined reference to libsocket::socket::destroy()'
/tmp/ccUUZQym.o:(.rodata._ZTVN9libsocket17unix_dgram_clientE[_ZTVN9libsocket17unix_dgram_clientE]+0x80): undefined reference to `libsocket::socket::destroy()'
collect2: error: ld returned 1 exit status

Fix: Put the -lsocket++ at the end of the g++ compiler lines, not in front of the source names.

Cannot compile http_epoll.cpp

➜  examples++ git:(master) ✗ ls
a.out                  echo_client_conn.cpp   framing.cpp  http_epoll.cpp  server.cpp              unix_dgram_client.cpp        unix_server_stream.cpp
client.cpp             echo_client_sndto.cpp  http_2.cpp   libsocket++.a   test.sh                 unix_dgram_server.cpp
dgram_over_stream.cpp  echo_server.cpp        http.cpp     libsocket++.so  unix_client_stream.cpp  unix_dgram_syslogclient.cpp
➜  examples++ git:(master) ✗ g++ http_epoll.cpp -std=c++17 -lsocket++
In file included from http_epoll.cpp:3:
../headers/epoll.hpp: In destructor ‘libsocket::epollset<SocketT>::~epollset()’:
../headers/epoll.hpp:127:5: error: there are no arguments to ‘close’ that depend on a template parameter, so a declaration of ‘close’ must be available [-fpermissive]
  127 |     close(epollfd);
      |     ^~~~~
../headers/epoll.hpp:127:5: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
http_epoll.cpp: In function ‘int main()’:
http_epoll.cpp:35:36: error: use of deleted function ‘libsocket::inet_stream& libsocket::inet_stream::operator=(const libsocket::inet_stream&)’
   35 |             sock = *(ready.first[0]);
      |                                    ^
In file included from http_epoll.cpp:5:
../headers/inetclientstream.hpp:54:7: note: ‘libsocket::inet_stream& libsocket::inet_stream::operator=(const libsocket::inet_stream&)’ is implicitly deleted because the default definition would be ill-formed:
   54 | class inet_stream : public inet_socket, public stream_client_socket {
      |       ^~~~~~~~~~~
../headers/inetclientstream.hpp:54:7: error: use of deleted function ‘libsocket::inet_socket& libsocket::inet_socket::operator=(const libsocket::inet_socket&)’
In file included from ../headers/inetclientstream.hpp:8,
                 from http_epoll.cpp:5:
../headers/inetbase.hpp:52:7: note: ‘libsocket::inet_socket& libsocket::inet_socket::operator=(const libsocket::inet_socket&)’ is implicitly deleted because the default definition would be ill-formed:
   52 | class inet_socket : public virtual socket {
      |       ^~~~~~~~~~~
../headers/inetbase.hpp:52:7: error: use of deleted function ‘constexpr libsocket::socket& libsocket::socket::operator=(const libsocket::socket&)’
In file included from ../headers/epoll.hpp:45,
                 from http_epoll.cpp:3:
../headers/socket.hpp:71:7: note: ‘constexpr libsocket::socket& libsocket::socket::operator=(const libsocket::socket&)’ is implicitly declared as deleted because ‘libsocket::socket’ declares a move constructor or move assignment operator
   71 | class socket {
      |       ^~~~~~
In file included from http_epoll.cpp:5:
../headers/inetclientstream.hpp:54:7: error: use of deleted function ‘libsocket::stream_client_socket& libsocket::stream_client_socket::operator=(const libsocket::stream_client_socket&)’
   54 | class inet_stream : public inet_socket, public stream_client_socket {
      |       ^~~~~~~~~~~
In file included from ../headers/inetclientstream.hpp:9,
                 from http_epoll.cpp:5:
../headers/streamclient.hpp:52:7: note: ‘libsocket::stream_client_socket& libsocket::stream_client_socket::operator=(const libsocket::stream_client_socket&)’ is implicitly declared as deleted because ‘libsocket::stream_client_socket’ declares a move constructor or move assignment operator
   52 | class stream_client_socket : public virtual socket {
      |       ^~~~~~~~~~~~~~~~~~~~
In file included from http_epoll.cpp:3:
../headers/epoll.hpp: In instantiation of ‘libsocket::epollset<SocketT>::~epollset() [with SocketT = libsocket::inet_stream]’:
http_epoll.cpp:23:31:   required from here
../headers/epoll.hpp:127:10: error: ‘close’ was not declared in this scope; did you mean ‘pclose’?
  127 |     close(epollfd);
      |     ~~~~~^~~~~~~~~
      |     pclose
➜  examples++ git:(master) ✗ 

"Resource temporarily unavailable" when receiving with a non blocking inet_dgram_server socket

Hi,

Here is the code:

libsocket::inet_dgram_server sock("localhost", "4000", LIBSOCKET_IPv4, SOCK_NONBLOCK);

if(sock.rcvfrom(ntwrk_buf, 1024, ntwrk_from, ntwrk_from_port) != -1)
{
    cout << "data received" << endl;
}

In the console it writes "Resource temporarily unavailable" when I launch this code. After some debugging, I found that this message is coming from check_error function called in recvfrom_inet_dgram_socket when recvfrom returns -1. But for a non blocking socket, it's not an issue, that's when we didn't receive any data.

I just deleted the call to check_error and the message is not shown anymore but I don't think that's the best thing to do. Did I miss something there to make a non blocking socket?

Thanks,

Arthur

error while run apps

error while loading shared libraries: libsocket.so: cannot open shared object file: No such file or directory

i got this while run compiled example.
i'm sure libsocket.so was located at /usr/lib
this is my compile command.
gcc -Wall -g -std=gnu99 -L/usr/lib -lsocket http.c -o app
my system is centos 7,

Undefined reference / Cannot find symbols

Hi there

I am trying to use the library (C version) in one of my projects but always get an error about missing symbols/references.

Do I have to do something special beside installing as stated in the README?

Tested on Debian 7 and Ubuntu 14.04 with g++, linking against libsocket.so.

Thanks for your help :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.