SimpleSockets is a lightweight set of classes that allow developers to implement IP based network programs.

Overview
------------------------------------------------------------------------------------------
* History
------------------------------------------------------------------------------------------
Written by Mark Carrier to provide a mechanism for writing cross platform socket code. This library was originally written to only support blocking TCP sockets. Over the years it has been extended to support UDP and RAW sockets as well. This is the first official release of the library and the following functionality is supported:

    * Cross platform socket support.
          o Windows 95, Windows 98, Windows XP
          o Linux, Unix
          o Macintosh OSX
    * Support for sychronious, and asychronious sockets
    * Supports TCP Streams
    * Supports UDP Datagrams
    * Supports Raw Sockets
    * Thread Safe
    * Signal Safe

------------------------------------------------------------------------------------------
* Building and Installing	
------------------------------------------------------------------------------------------
This is a very small library and is very easy to build and configure.  To build and install
make sure you are logged in as a user who has access to the recommend GNU installation 
directories. Then type

make -BUILD=Release && make install

That is it now you are off and running.

NOTE: When using the library with WINDOWS you must define _WIN32 and when using with LINUX
      you must define _LINUX.

------------------------------------------------------------------------------------------
* SimpleSocket Class Overview
------------------------------------------------------------------------------------------
Network communications via sockets can be abstracted into two categories of functionality; the active socket and the passive socket. The active socket object initiates a connection with a known host, whereas the passive socket object waits (or listens) for inbound requests for communication. The functionality of both objects is identical as far as sending and receiving data. This library makes distinction between the two objects because the operations for constructing and destructing the two are different.

This library is different from other socket libraries which define TCP sockets, UDP sockets, HTTP sockets, etc. The reason is the operations required for TCP, UDP, and RAW network communication is identical from a logical stand point. Thus a program could initially be written employing TCP streams, and then at some future point it could be discovered that UDP datagrams would satisify the solution. Changing between the two transport protocols would only require changing how the object is instantiated. The remaining code would in theory require minimal to no changes.

This library avoids abstractions like HTTP socket, or SMTP socket, soley because this type of object mixes the application and the transport layer. These types of abstractions can be created using this library as a base class.

The simple socket library is comprised of two class which can be used to represent all socket communications.

    * Active Socket Class
    * Passive Socket Class 


------------------------------------------------------------------------------------------
* SimpleSocket Class Examples
------------------------------------------------------------------------------------------
When operating on a socket object most methods will return true or false
Simple Active Socket
As mentioned previously the active socket (CActiveSocket) is used to initiate a connections with a server on some known port. So you want to connect to an existing server...

How do you do it?

There are many ways using the existing Berkley Socket API, but the goal of this class is to remove the many calls and man page lookups and replace them with clear, concise set of methods which allow a developer to focus on the logic of network programming.

The following code will connect to a DAYTIME server on port 13, query for the current time, and close the socket.

#include <string.h>
#include "ActiveSocket.h"       // Include header for active socket object definition

int main(int argc, char **argv)
{
    CActiveSocket socket;       // Instantiate active socket object (defaults to TCP).
    char          time[50];

    memset(&time, 0, 50);

    //--------------------------------------------------------------------------
    // Initialize our socket object 
    //--------------------------------------------------------------------------
    socket.Initialize();

    //--------------------------------------------------------------------------
    // Create a connection to the time server so that data can be sent
    // and received.
    //--------------------------------------------------------------------------
    if (socket.Open("time-C.timefreq.bldrdoc.gov", 13))
    {
        //----------------------------------------------------------------------
        // Send a requtest the server requesting the current time.
        //----------------------------------------------------------------------
        if (socket.Send((const uint8 *)"\n", 1))
        {
            //----------------------------------------------------------------------
            // Receive response from the server.
            //----------------------------------------------------------------------
            socket.Receive(49);
            memcpy(&time, socket.GetData(), 49);
            printf("%s\n", time);

            //----------------------------------------------------------------------
            // Close the connection.
            //----------------------------------------------------------------------
            socket.Close();
        }
    }


    return 1;
}

You can see that the amount of code required to an object for network communciation is very small and simple.
Simple Passive Socket
Now you want to build a server.

How do you do it?

For a practical test lets build an echo server. The server will listen on port 6789 an repsond back with what ever has been sent to the server.

#include "PassiveSocket.h"       // Include header for active socket object definition

#define MAX_PACKET 4096 

int main(int argc, char **argv)
{
    CPassiveSocket socket;
    CActiveSocket *pClient = NULL;

    //--------------------------------------------------------------------------
    // Initialize our socket object 
    //--------------------------------------------------------------------------
    socket.Initialize();

    socket.Listen("127.0.0.1", 6789);

    while (true)
    {
        if ((pClient = socket.Accept()) != NULL)
        {
            //----------------------------------------------------------------------
            // Receive request from the client.
            //----------------------------------------------------------------------
            if (pClient->Receive(MAX_PACKET))
            {
                //------------------------------------------------------------------
                // Send response to client and close connection to the client.
                //------------------------------------------------------------------
                pClient->Send( pClient->GetData(), pClient->GetBytesReceived() );
                pClient->Close();
            }

            delete pClient;
        }
    }

    //-----------------------------------------------------------------------------
    // Receive request from the client.
    //-----------------------------------------------------------------------------
    socket.Close();

    return 1;
}
Comments
  • Include example covering error handling

    Include example covering error handling

    Using a simple:

    networkConnection->TranslateSocketError();
    CSimpleSocket::CSocketError e = networkConnection->GetSocketError();
    networkConnection->DescribeError(e);
    

    Has seemed to error every time. Also, I've been getting -1 from networkConnection->Receive() and when checking the error using the above code, the error is CSimpleSocket::CSocketError::SocketSuccess.

    opened by TheGreatRambler 5
  • MSVC: Fix generation of clsocket.lib

    MSVC: Fix generation of clsocket.lib

    When building the library on Windows with the Visual Studio compiler, clsocket.dll is generated correctly but clsocket.lib (the Import Library for use by programs linking with it) isn't generated at all because nothing is exported from the library.

    This PR fixes this by adding an __declspec(dllexport) clause to the library's classes. This clause is abstracted behind an EXPORT conditional define, so that different platforms can use different export behaviors.

    opened by Palakis 3
  • "fixed" types for port number and window size

    please have a look at the changes.

    cause of incompatible interface / function prototypes it might be necessary to change the version number(s) in CMakeLists.txt. I did not do this, cause i don't know which version would be desired. really change major version?

    then, i also replaced the type for most connect/address strings, except for data.

    opened by hayguen 3
  • CSimpleSocket::Shutdown ignores CShutdownMode-Parameter

    CSimpleSocket::Shutdown ignores CShutdownMode-Parameter

    SimpleSocket.cpp, 502 is nRetVal = (CSocketError)shutdown(m_socket, CSimpleSocket::Sends); but must be nRetVal = (CSocketError)shutdown(m_socket, nShutdown);

    opened by juliusbaechle 1
  • Great Library! - Windows timing question ?

    Great Library! - Windows timing question ?

    Hello Mark, The clsocket library looks well structured and suited to handle many socket applications in one shot. I like it a lot! I also like the abundance of comments ! Fantastic ! Just one question: In the CStatTimer class I see you don't QueryPerformanceFrequency for WIN32. How do you get accurate time based counts without doing that ? Whats the secret ? The way understand QueryPerformanceCounter just gets a count/tick...but you need to combine it with the Frequency to get a time based count ? Thanks & Cheers

    opened by Percell007 1
  • travis: test against GCC 4.4 instead of 4.5

    travis: test against GCC 4.4 instead of 4.5

    Ubuntu Trusty is now the default image on Travis, and Trusty doesn't have any GCC 4.5 packages. See https://bugs.launchpad.net/ubuntu/+source/gcc-4.5/+bug/1028213 and https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=675431 for more information.

    opened by ligfx 1
  • CMake integration available only after install

    CMake integration available only after install

    When trying to use clsocket without installing it (e.g. with FetchContent), include path is not set and compilation fails. With following dummy example: main.cpp:

    #include <PassiveSocket.h>
    int main() {}
    

    CMakeLists.txt:

    project(test_clsocket_cmake LANGUAGES CXX)
    set(CMAKE_CXX_STANDARD 17)
    
    include(FetchContent)
    FetchContent_Declare(
        clsocket
        GIT_REPOSITORY https://github.com/DFHack/clsocket.git
    )
    option(CLSOCKET_SHARED Off)
    option(CLSOCKET_DEP_ONLY Off)
    FetchContent_MakeAvailable(clsocket)
    
    set(app_ ${PROJECT_NAME})
    add_executable(${app_} main.cpp)
    target_link_libraries(${app_} clsocket)
    

    Pre-build cmake stage passes fine, but the build fails:

    [main] Building folder: clsocket-cmake
    [build] Starting build
    [proc] Executing command: /Users/me/brew/bin/cmake --build /Users/me/src/clsocket-cmake/build --config Debug --target all --
    [build] [1/2  50% :: 0.057] Building CXX object CMakeFiles/test_clsocket_cmake.dir/main.o
    [build] FAILED: CMakeFiles/test_clsocket_cmake.dir/main.o
    [build] /usr/bin/clang++   -g -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -std=gnu++17 -MD -MT CMakeFiles/test_clsocket_cmake.dir/main.o -MF CMakeFiles/test_clsocket_cmake.dir/main.o.d -o CMakeFiles/test_clsocket_cmake.dir/main.o -c /Users/me/src/clsocket-cmake/main.cpp
    [build] /Users/me/src/clsocket-cmake/main.cpp:1:10: fatal error: 'PassiveSocket.h' file not found
    [build] #include <PassiveSocket.h>
    [build]          ^~~~~~~~~~~~~~~~~
    [build] 1 error generated.
    [build] ninja: build stopped: subcommand failed.
    [proc] The command: /Users/me/brew/bin/cmake --build /Users/me/src/clsocket-cmake/build --config Debug --target all -- exited with code: 1 and signal: null
    [build] Build finished with exit code 1
    
    opened by v-val 0
  • Set VERSION and SONAME version properties from CMake

    Set VERSION and SONAME version properties from CMake

    If clsocket is compiled dynamically, this will produce .so files with the version in their name, e.g. libclsocket.so.1.4.3, to which libclsocket.so.1 and libclsocket.so is symlinked to. This means that if anyone wants to use this dynamically, they will nominally be able to better ensure ABI compatibility.

    Since the version was already included in the CMake configuration, this is a very simple change.

    Since dfhack is linking against clsocket statically, this shouldn't affect it at all, but this change should help anyone who wants to use clsocket as a dynamic library (or build dfhack against a dynamic clsocket for whatever reason).

    opened by TC01 0
  • WSACleanup not called

    WSACleanup not called

    In CSimpleSocket::Initialize the m_hWSAData is initialised under Windows using WSAStartup. According to MSDN, each call to WSAStartup must have a matching call to WSACleanup. However, the entire library is lacking such a call: https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup

    When frequently creating sockets, sending data, closing and destroying sockets, this might cause resource leaks.

    Is this just an oversight? Best regards

    opened by BongoVR 0
  • EXPORT definition might collide easily

    EXPORT definition might collide easily

    #define EXPORT __declspec(dllexport)
    

    is defined in Host.h include from other public headers (SimpleSocket.h), with guard #ifdef _MSC_VER. however this definition might collide easily with user code using CLsocket.

    i'd suggest to rename EXPORT into CLSOCKET_EXPORT .. [ and possibly make this definition only when having an additional private definition in CMakeLists.txt, e.g. when compiling the shared library ]

    opened by hayguen 3
  • CPassiveSocket::Listen() behaves different on Windows

    CPassiveSocket::Listen() behaves different on Windows

    On Windows,

        SETSOCKOPT(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&nReuse, sizeof(int32));
        SETSOCKOPT(m_socket, IPPROTO_TCP, IP_TOS, &nReuse, sizeof(int32));
    

    is NOT executed, where especially setting SO_REUSEADDR leads to different behaviour, when closing listening socket .. and trying to listen again within a few seconds.

    same behaviour could be achieved, when always calling CSimpleSocket::SetOptionReuseAddr()

    always inside Listen() - as alternative, have it called from outside before calling Listen() - if desired.

    The same issue also for IPPROTO_TCP / IP_TOS but this function is missing in CSimpleSocket - for now.

    opened by hayguen 0
  • Install failing on visual studio 2017

    Install failing on visual studio 2017

    The install is failing on visual studio 2017, on windows 7. I get the following error:

    [1/2] Linking CXX shared library clsocket-CMAKE\clsocket.dll
    FAILED: clsocket-CMAKE/clsocket.dll clsocket-CMAKE/clsocket.lib 
    cmd.exe /C "cd . && "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E vs_link_dll --intdir=clsocket-CMAKE\CMakeFiles\clsocket.dir --manifests  -- C:\PROGRA~2\MIB055~1\2017\PROFES~1\VC\Tools\MSVC\1414~1.264\bin\Hostx86\x86\link.exe /nologo clsocket-CMAKE\CMakeFiles\clsocket.dir\src\SimpleSocket.obj clsocket-CMAKE\CMakeFiles\clsocket.dir\src\ActiveSocket.obj clsocket-CMAKE\CMakeFiles\clsocket.dir\src\PassiveSocket.obj  /out:clsocket-CMAKE\clsocket.dll /implib:clsocket-CMAKE\clsocket.lib /pdb:clsocket-CMAKE\clsocket.pdb /dll /version:4.0 /machine:X86 /debug /INCREMENTAL  Ws2_32.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib  && cd ."
    RC Pass 1: command "rc /foclsocket-CMAKE\CMakeFiles\clsocket.dir/manifest.res clsocket-CMAKE\CMakeFiles\clsocket.dir/manifest.rc" failed (exit code 0) with the following output:
    The system cannot find the file specified
    ninja: build stopped: subcommand failed.
    Install failed.
    
    opened by UHSL-Marcus 3
Owner
DFHack
Pushing DFHack forward!
DFHack
traces tcp requests in kernel. allow to set up IPs to filter dynamically using bpf-map.

ttcp cilium/ebpf/examples/tcprtt에다가 BPF_MAP_TYPE_HASH를 추가해서 srcAddr을 필터링하도록 수정함. 어플리케이션에는 Http API를 추가해서 필터링할 IP를 추가, 삭제, 조회할 수 있도록 함. Getting Startd

null 8 May 20, 2022
single header C(99) library to implement client-server network code for games

single header C(99) library to implement client-server network code for games

Nathan 227 Nov 25, 2022
Linux Terminal Service Manager (LTSM) is a set of service programs that allows remote computers to connect to a Linux operating system computer using a remote terminal session (over VNC or RDP)

Linux Terminal Service Manager (LTSM) is a set of service programs that allows remote computers to connect to a Linux operating system computer using a remote terminal session (over VNC)

null 33 Nov 28, 2022
The purpose of this application is to allow a chronological shuffling of tv shows. The selected TV Shows maybe shuffled however the episodes will be selected based on next unwatched.

TvShuffleForPlex Description The purpose of this application is to allow a chronological shuffling of tv shows. The selected TV Shows maybe shuffled h

null 16 Apr 4, 2022
The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.

Welcome! The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design

Microsoft 7.1k Nov 26, 2022
A modern C++ network library for developing high performance network services in TCP/UDP/HTTP protocols.

evpp Introduction 中文说明 evpp is a modern C++ network library for developing high performance network services using TCP/UDP/HTTP protocols. evpp provid

Qihoo 360 3.1k Nov 29, 2022
XMap is a fast network scanner designed for performing Internet-wide IPv6 & IPv4 network research scanning.

XMap is reimplemented and improved thoroughly from ZMap and is fully compatible with ZMap, armed with the "5 minutes" probing speed and novel scanning techniques. XMap is capable of scanning the 32-bits address space in under 45 minutes.

idealeer 189 Nov 23, 2022
Header-only C++14 library for getting network addresses associated with network interface without name lookups on Windows, macOS, Linux, and FreeBSD

NetIF Get addresses associated with network interfaces on a system without using name lookups. Header-only, requires C++14. Usage Add the header file

GMLC-TDC 9 Oct 17, 2022
Netif - Header-only C++14 library for getting network addresses associated with network interface without name lookups on Windows, macOS, Linux, and FreeBSD

NetIF Get addresses associated with network interfaces on a system without using name lookups. Header-only, requires C++14. Usage Add the header file

GMLC-TDC 9 Oct 17, 2022
An SFTP client shared library (dll/so/dylib) with bindings and classes for C++, Delphi and Free Pascal based on PuTTY

TGPuttyLib A shared library / DLL with Delphi and C++ bindings based on PuTTY, for Windows, macOS, and Linux. The new TGPuttyLib SFTP Library is a DLL

Tobias Giesen 71 Nov 22, 2022
Implement Ipv4 ServiceId Table() based on INET framework on OMNeT++.

omnet++/inet_Service-Id-Table Implement Ipv4 ServiceId Table(<ipaddr,sid>) based on INET framework on OMNeT++. Version: OMNeT++ 5.6.2(https://github.c

null 1 May 28, 2022
Source-code based coverage for eBPF programs actually running in the Linux kernel

bpfcov Source-code based coverage for eBPF programs actually running in the Linux kernel This project provides 2 main components: libBPFCov.so - an ou

elastic 112 Nov 9, 2022
Minimalistic server (written in C) and a python3 client to allow calling C function on a remote host

Minimalistic server (written in C) and a python3 client to allow calling C function on a remote host

null 17 Nov 9, 2022
A cross-platform SDK enabling developers to integrate real-time chat technology into their projects

4Players ODIN SDK ODIN is a cross-platform software development kit (SDK) that enables developers to integrate real-time chat technology into multipla

4Players 5 Oct 28, 2022
Pushpin is a reverse proxy server written in C++ that makes it easy to implement WebSocket, HTTP streaming, and HTTP long-polling services.

Pushpin is a reverse proxy server written in C++ that makes it easy to implement WebSocket, HTTP streaming, and HTTP long-polling services. The project is unique among realtime push solutions in that it is designed to address the needs of API creators. Pushpin is transparent to clients and integrates easily into an API stack.

Fanout 3.2k Nov 24, 2022
A Nginx module which tries to implement proxy wasm ABI in Nginx.

Status This library is under construction. Description A Nginx module which tries to implement proxy wasm ABI in Nginx. Install dependencies Download

API7 99 Nov 19, 2022
A Rust crate that simplifies the integration of Rust and eBPF programs written in C.

This crate simplifies the compilation of eBPF programs written in C integrating clang with Rust and the cargo build system with functions that can be

Simone Margaritelli 19 Mar 16, 2022
XDP programs that increment stat counters for packets/bytes.

XDP Stats Description This is a program that calculates stats inside of an XDP program (support for both XDP_DROP and XDP_TX). As of right now, the st

Christian Deacon 10 Oct 30, 2022
Extract TLS session keys from running programs

Tlskeydump Tlskeydump extracts TLS key material from processes at runtime so that packet captures containing TLS-encrypted data can be decrypted and a

Konstantinos Tsanaktsidis 7 Sep 5, 2022