C++17 • Open Source • MIT License

High-Performance P2P Networking for Modern Applications

Enterprise-grade peer-to-peer networking library with advanced NAT traversal, end-to-end encryption, and publish-subscribe messaging. Built from the ground up in C++17 with comprehensive C, Java, and Android support.

50x
Less Memory
99%
NAT Success
1.6MB
Footprint

Enterprise-Grade Features

Everything you need for robust P2P networking

Advanced NAT Traversal

ICE, STUN, and TURN support with 99%+ success rate across any network topology. Automatic strategy selection for optimal connectivity.

RFC Compliant

End-to-End Encryption

Noise Protocol implementation with Curve25519 + ChaCha20-Poly1305. Automatic key management and perfect forward secrecy.

Noise Protocol

GossipSub Messaging

Scalable publish-subscribe messaging with mesh networking. Topic-based communication and message validation.

Pub/Sub

File Transfer

Chunked transfers with resume capability. Directory transfer support with parallel transmission and integrity verification.

Resumable

Multi-Layer Discovery

DHT integration, mDNS local discovery, and STUN-based public IP discovery. Automatic peer reconnection.

Auto Discovery

High Performance

Native C++17 implementation with zero-copy operations. Thread-safe design and minimal memory footprint.

50x Faster

Quick Start

Get up and running in minutes

Basic P2P Connection
#include "librats.h"
#include <iostream>
#include <thread>
#include <chrono>

int main() {
    // Create a simple P2P client
    librats::RatsClient client(8080);
    
    // Set up connection callback
    client.set_connection_callback([](socket_t socket, const std::string& peer_id) {
        std::cout << "✅ New peer connected: " << peer_id << std::endl;
    });
    
    // Set up message callback
    client.set_string_data_callback([](socket_t socket, const std::string& peer_id, const std::string& message) {
        std::cout << "💬 Message from " << peer_id << ": " << message << std::endl;
    });
    
    // Start the client
    if (!client.start()) {
        std::cerr << "Failed to start client" << std::endl;
        return 1;
    }
    
    std::cout << "🐀 librats client running on port 8080" << std::endl;
    
    // Connect to another peer (optional)
    // client.connect_to_peer("127.0.0.1", 8081);
    
    // Send a message to all connected peers
    client.broadcast_string_to_peers("Hello from librats!");
    
    // Keep running
    std::this_thread::sleep_for(std::chrono::minutes(1));
    
    return 0;
}
Custom Protocol Setup
#include "librats.h"
#include <iostream>

int main() {
    librats::RatsClient client(8080);
    
    // Configure custom protocol for your application
    client.set_protocol_name("my_app");
    client.set_protocol_version("1.0");
    
    std::cout << "Protocol: " << client.get_protocol_name() 
              << " v" << client.get_protocol_version() << std::endl;
    std::cout << "Discovery hash: " << client.get_discovery_hash() << std::endl;
    
    client.start();
    
    // Start DHT discovery with custom protocol
    if (client.start_dht_discovery()) {
        // Announce our presence
        client.announce_for_hash(client.get_discovery_hash());
        
        // Search for other peers using same protocol
        client.find_peers_by_hash(client.get_discovery_hash(), 
            [](const std::vector<std::string>& peers) {
                std::cout << "Found " << peers.size() << " peers" << std::endl;
            });
    }
    
    return 0;
}
Chat Application with Message Exchange API
#include "librats.h"
#include <iostream>
#include <string>

int main() {
    librats::RatsClient client(8080);
    
    // Set up message handlers using the modern API
    client.on("chat", [](const std::string& peer_id, const nlohmann::json& data) {
        std::cout << "[CHAT] " << peer_id << ": " 
                  << data["message"].get<std::string>() << std::endl;
    });
    
    client.on("user_join", [](const std::string& peer_id, const nlohmann::json& data) {
        std::cout << "[JOIN] " << data["username"].get<std::string>() 
                  << " joined" << std::endl;
    });
    
    // Connection callback
    client.set_connection_callback([&](socket_t socket, const std::string& peer_id) {
        std::cout << "✅ Peer connected: " << peer_id << std::endl;
        
        // Send welcome message
        nlohmann::json welcome;
        welcome["username"] = "User_" + client.get_our_peer_id().substr(0, 8);
        client.send("user_join", welcome);
    });
    
    client.start();
    
    // Send a chat message
    nlohmann::json chat_msg;
    chat_msg["message"] = "Hello, P2P chat!";
    chat_msg["timestamp"] = std::time(nullptr);
    client.send("chat", chat_msg);
    
    return 0;
}
GossipSub Messaging
int main() {
    librats::RatsClient client(8080);
    
    // Set up topic message handlers
    client.on_topic_message("chat", [](const std::string& peer_id, 
        const std::string& topic, const std::string& message) {
        std::cout << "Chat from " << peer_id << ": " << message << std::endl;
    });
    
    client.on_topic_json_message("events", [](const std::string& peer_id, 
        const std::string& topic, const nlohmann::json& data) {
        std::cout << "Event: " << data["type"] << " from " << peer_id << std::endl;
    });
    
    // Set message validator
    client.set_topic_message_validator("chat", [](const std::string& topic, 
        const std::string& message, const std::string& peer_id) {
        // Only accept messages shorter than 1000 characters
        return message.length() <= 1000 ? 
            librats::ValidationResult::ACCEPT : 
            librats::ValidationResult::REJECT;
    });
    
    client.start();
    client.start_dht_discovery();
    
    // Subscribe to topics
    client.subscribe_to_topic("chat");
    client.subscribe_to_topic("events");
    
    // Publish messages
    client.publish_to_topic("chat", "Hello, GossipSub world!");
    
    nlohmann::json event_data;
    event_data["type"] = "user_login";
    event_data["timestamp"] = std::time(nullptr);
    client.publish_json_to_topic("events", event_data);
    
    return 0;
}
File Transfer
#include "librats.h"
#include <iostream>

int main() {
    librats::RatsClient client(8080);
    
    // Set up file transfer callbacks
    client.on_file_transfer_progress([](const librats::FileTransferProgress& progress) {
        std::cout << "\ud83d\udcc1 Transfer " << progress.transfer_id.substr(0, 8) 
                  << ": " << progress.get_completion_percentage() << "% complete"
                  << " (" << (progress.transfer_rate_bps / 1024) << " KB/s)" << std::endl;
    });
    
    client.on_file_transfer_completed([](const std::string& transfer_id, bool success, const std::string& error) {
        if (success) {
            std::cout << "\u2705 Transfer completed: " << transfer_id.substr(0, 8) << std::endl;
        } else {
            std::cout << "\u274c Transfer failed: " << error << std::endl;
        }
    });
    
    // Auto-accept incoming file transfers
    client.on_file_transfer_request([](const std::string& peer_id, 
                                      const librats::FileMetadata& metadata, 
                                      const std::string& transfer_id) {
        std::cout << "\ud83d\udce5 Incoming: " << metadata.filename << " from " << peer_id.substr(0, 8) << std::endl;
        return true; // Auto-accept
    });
    
    client.start();
    
    // Configure transfer settings
    librats::FileTransferConfig config;
    config.chunk_size = 64 * 1024;       // 64KB chunks
    config.max_concurrent_chunks = 4;    // 4 parallel chunks
    config.verify_checksums = true;      // Verify integrity
    client.set_file_transfer_config(config);
    
    std::cout << "File transfer ready. Connect peers and exchange files!" << std::endl;
    
    // Example transfers (replace "peer_id" with actual peer ID)
    //std::string file_transfer = client.send_file("peer_id", "my_file.txt");
    //std::string dir_transfer = client.send_directory("peer_id", "./my_folder");
    //std::string file_request = client.request_file("peer_id", "remote_file.txt", "./downloaded_file.txt");

    return 0;
}

Exceptional Performance

Engineered for efficiency and resource optimization

librats vs libp2p (JavaScript)

Test Environment: AMD Ryzen 7 5700U, 16GB RAM

Startup Memory
1.6 MB
vs
50-80 MB
31-50x less memory
Memory per Peer
80 KB
vs
4-6 MB
50-75x more efficient
CPU Usage (idle)
0-1%
vs
15-25%
15-25x less CPU
Peak Memory (100 peers)
9.4 MB
vs
400-600 MB
42-64x less memory

Industry-Leading NAT Traversal

Connect across virtually any network topology

NAT Type Direct STUN ICE TURN Success Rate
Open Internet 100%
Full Cone NAT 95%
Restricted Cone 90%
Port Restricted 85%
Symmetric NAT ⚠️ 70%
Double NAT 99%

Download librats

Get the latest version for your platform

Latest Release v0.3.0

Windows

Windows 10/11 (x64)

Requires: Visual C++ Redistributable 2019+

macOS

macOS 10.15+ (Universal)

Intel & Apple Silicon supported

Linux

Ubuntu 18.04+ / CentOS 7+

glibc 2.27+ required

Build from Source

Compile librats yourself for maximum compatibility

git clone https://github.com/DEgITx/librats.git
cd librats
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)

Supported Platforms & Language Bindings

Cross-platform support with bindings for multiple programming languages

Native C++ Support

Production-ready implementations across all major platforms

Platform Build Environment Compiler Status
Windows
MinGW-w64 GCC 7+ Fully Supported
Windows
Visual Studio MSVC 2017+ Fully Supported
Linux
Native GCC 7+, Clang 5+ Fully Supported
macOS
Xcode/Native Clang 10+ Fully Supported

Language Bindings & Wrappers

Multi-language support for diverse development ecosystems

Language/Platform Binding Type Status Timeline Notes
C/C++
Native Library Fully Supported Available Now Core implementation with full feature set
Android (NDK)
Native C++ Fully Supported Available Now Android NDK integration with JNI bindings
Android (Java)
JNI Wrapper Fully Supported Available Now High-level Java API for Android apps
JavaScript
Native Module Planned Soon Node.js native addon with async/await support
Python
C Extension Planned Soon CPython extension with asyncio integration
Rust
FFI Bindings Planned Soon Safe Rust bindings with tokio async support
Go
CGO Bindings Future Soon CGO wrapper for Go applications
C#/.NET
P/Invoke Future Soon .NET bindings for Windows/Linux/macOS

Mobile Platform Support

Native mobile development for iOS and Android

Android

NDK + JNI Implementation

Fully Supported
  • Full P2P networking
  • File transfer
  • GossipSub messaging

iOS

Native C++ Implementation

Planned
  • Swift/Objective-C bindings planned
  • Full feature parity with Android
  • App Store compatible

Cross-Platform Mobile Frameworks

React Native
Future
Flutter
Future

Web Platform Support

Web and desktop application development

Browser (WASM)

WebAssembly Implementation

Research
Limited by browser networking APIs

Electron

Node.js Module

Planned
Desktop app development

Tauri

Rust Bindings

Future
Lightweight desktop apps

Status Legend

Fully Supported Production-ready with comprehensive testing
In Development Active development, preview/beta available
Planned Confirmed for development, timeline estimated
Future Under consideration, timeline not confirmed
Research Investigating feasibility and implementation

Comprehensive Documentation

Everything you need to get started and build amazing P2P applications