Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

LAN Mesh Chat

A lightweight, decentralized peer-to-peer mesh network chat application built in Python. No central server required - each peer acts as both client and server, creating a resilient mesh topology where messages propagate across the entire network.

Project Overview

LAN Mesh Chat implements a true mesh network architecture where peers automatically forward messages to all connected nodes. The application uses TCP sockets for reliable message delivery and JSON for message serialization. Built-in message deduplication prevents infinite loops, while the mesh topology ensures high availability - the network continues to function even if individual nodes disconnect.

Key Characteristics:

  • Pure Python implementation with no external dependencies
  • Decentralized architecture with no single point of failure
  • Automatic message routing and forwarding
  • Thread-safe concurrent connection handling
  • Real-time message broadcasting across the mesh

Features

  • True Mesh Networking: Each peer can connect to multiple other peers, creating a resilient network topology
  • Automatic Message Forwarding: Messages automatically propagate to all peers through the mesh
  • Message Deduplication: UUID-based tracking prevents duplicate messages and infinite loops
  • Zero Configuration: No central server or complex setup required
  • Multi-threaded Architecture: Concurrent handling of multiple peer connections
  • Connection Management: Automatic detection and cleanup of dead connections
  • Simple Commands: Built-in /quit and /peers commands for easy management
  • Timestamped Messages: All messages include timestamps for conversation context
  • Cross-platform: Works on Linux, macOS, and Windows

Installation

Prerequisites

  • Python 3.6 or higher
  • No external dependencies required (uses only Python standard library)

Setup

  1. Clone or download the application:
git clone <repository-url>
cd lan-mesh-chat
  1. Make the script executable (Linux/macOS):
chmod +x lan_mesh_chat.py
  1. Verify Python version:
python3 --version

That's it! The application uses only Python's standard library, so no pip install is needed.

Quick Start

Basic Two-Peer Setup

Terminal 1 (First peer - Alice):

python3 lan_mesh_chat.py --port 5000 --name Alice

Terminal 2 (Second peer - Bob, connecting to Alice):

python3 lan_mesh_chat.py --port 5001 --name Bob --peers localhost:5000

Now type messages in either terminal and watch them appear in both!

Three-Peer Mesh Network

Terminal 1 (Alice):

python3 lan_mesh_chat.py --port 5000 --name Alice

Terminal 2 (Bob):

python3 lan_mesh_chat.py --port 5001 --name Bob --peers localhost:5000

Terminal 3 (Charlie):

python3 lan_mesh_chat.py --port 5002 --name Charlie --peers localhost:5000,localhost:5001

Charlie connects to both Alice and Bob, creating a fully connected mesh. Messages sent by any peer reach all others.

Detailed Usage

Command-Line Options

python3 lan_mesh_chat.py [OPTIONS]
Option Short Required Default Description
--port -p No 5000 Port number to listen on for incoming connections
--name -n Yes - Your display name in the chat
--peers - No - Comma-separated list of peers to connect to (format: host:port)

Examples

Example 1: Single Peer (Waiting for Connections)

python3 lan_mesh_chat.py --port 5000 --name Alice

Alice starts listening on port 5000, waiting for other peers to connect.

Example 2: Connect to Existing Peer

python3 lan_mesh_chat.py --port 5001 --name Bob --peers 192.168.1.100:5000

Bob starts on port 5001 and immediately connects to Alice at IP 192.168.1.100.

Example 3: Multi-Peer Connection

python3 lan_mesh_chat.py --port 5002 --name Charlie --peers 192.168.1.100:5000,192.168.1.101:5001

Charlie connects to multiple peers simultaneously, joining an existing mesh network.

Example 4: Remote Network (Replace with actual IPs)

# On Machine 1 (192.168.1.50)
python3 lan_mesh_chat.py --port 5000 --name Alice

# On Machine 2 (192.168.1.51)
python3 lan_mesh_chat.py --port 5000 --name Bob --peers 192.168.1.50:5000

# On Machine 3 (192.168.1.52)
python3 lan_mesh_chat.py --port 5000 --name Charlie --peers 192.168.1.50:5000,192.168.1.51:5000

In-Chat Commands

Once connected, you can use these commands:

Command Description
/quit Exit the chat application gracefully
/peers Display a list of currently connected peers
Any other text Broadcast the message to all peers in the mesh

Chat Interface

============================================================
  LAN Mesh Chat - Connected as 'Alice'
============================================================
Commands:
  /quit - Exit the chat
  /peers - List connected peers
  Type a message and press Enter to broadcast
============================================================

[14:32:15] Alice (you): Hello everyone!
[14:32:18] Bob: Hi Alice!
[14:32:21] Charlie: Hey folks!

How It Works

Mesh Network Architecture

LAN Mesh Chat implements a true peer-to-peer mesh topology:

    Alice (5000) ←──────→ Bob (5001)
         ↑                    ↑
         │                    │
         └────→ Charlie ←─────┘
              (5002)

Key Concepts:

  1. Dual Role: Each peer acts as both a server (accepting connections) and a client (initiating connections)

  2. Message Propagation: When a peer sends a message:

    • The message is assigned a unique UUID
    • It's broadcast to all directly connected peers
    • Each receiving peer forwards it to their connections
    • UUID tracking prevents infinite loops
  3. Thread Architecture:

    • Server Thread: Listens for incoming peer connections
    • Client Threads: Maintain outgoing connections to peers
    • Handler Threads: Process messages from each connection
    • Main Thread: Handles user input and broadcasting

Message Format

Messages are JSON objects sent over TCP:

{
  "msg_id": "550e8400-e29b-41d4-a716-446655440000",
  "sender": "Alice",
  "content": "Hello, mesh network!",
  "timestamp": "2026-02-08T14:32:15.123456"
}

Deduplication Algorithm

  1. Each message gets a unique UUID when created
  2. Every peer maintains a set of seen message IDs
  3. When receiving a message:
    • Check if UUID exists in seen set
    • If yes: discard (already processed)
    • If no: display, mark as seen, and forward to other peers
  4. Seen set is capped at 1,000 messages to prevent memory bloat

Connection Management

  • Auto-detection: Dead connections are automatically detected and cleaned up
  • Duplicate Prevention: Peers track connections by address to prevent duplicates
  • Thread-Safe: All connection operations use locks for thread safety
  • Graceful Shutdown: Ctrl+C cleanly closes all connections

Troubleshooting

Common Issues and Solutions

1. "Address already in use" Error

Problem: The port is already being used by another application.

Solutions:

# Check what's using the port
lsof -i :5000  # macOS/Linux
netstat -ano | findstr :5000  # Windows

# Use a different port
python3 lan_mesh_chat.py --port 5005 --name Alice

2. Cannot Connect to Peer

Problem: Connection refused or timeout when connecting to remote peer.

Diagnostics:

# Test if peer is reachable
ping 192.168.1.100

# Test if port is open
telnet 192.168.1.100 5000  # Linux/macOS
Test-NetConnection -ComputerName 192.168.1.100 -Port 5000  # Windows PowerShell

# Check firewall
sudo ufw status  # Linux
# Make sure port is allowed through firewall

Solutions:

  • Verify the peer's IP address is correct
  • Check that the peer's application is running
  • Ensure firewall allows the port:
    # Linux (UFW)
    sudo ufw allow 5000/tcp
    
    # Linux (iptables)
    sudo iptables -A INPUT -p tcp --dport 5000 -j ACCEPT
  • Try using 0.0.0.0 or specific IP instead of localhost for LAN access

3. Messages Not Appearing

Problem: Peers are connected but messages don't appear.

Solutions:

  • Check /peers command to verify connections
  • Look for error messages in the terminal
  • Restart peers in correct order (server peer first)
  • Verify network connectivity between machines

4. "Permission Denied" on Port

Problem: Cannot bind to port (typically ports below 1024).

Solutions:

# Use a port above 1024 (recommended)
python3 lan_mesh_chat.py --port 5000 --name Alice

# OR run with sudo (not recommended for security reasons)
sudo python3 lan_mesh_chat.py --port 80 --name Alice

5. Firewall Blocking Connections

Problem: Peers on different machines cannot connect.

Solutions:

Linux (UFW):

sudo ufw allow 5000/tcp
sudo ufw reload

Linux (firewalld):

sudo firewall-cmd --add-port=5000/tcp --permanent
sudo firewall-cmd --reload

macOS:

# Add rule in System Preferences > Security & Privacy > Firewall > Firewall Options
# Or temporarily disable: sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off

Windows:

# Run as Administrator
New-NetFirewallRule -DisplayName "LAN Mesh Chat" -Direction Inbound -Protocol TCP -LocalPort 5000 -Action Allow

6. Finding Your IP Address

Problem: Don't know what IP to use for --peers.

Solutions:

# Linux/macOS
ip addr show  # or ifconfig
hostname -I

# Windows
ipconfig

# Look for your LAN IP (usually 192.168.x.x or 10.x.x.x)

7. Mesh Network Not Forming

Problem: Peers connect but messages don't propagate through the mesh.

Diagnostics:

  • Use /peers command on each peer to see connection counts
  • Check for error messages about forwarding failures
  • Verify all peers are running the same version

Solutions:

  • Ensure each peer connects to at least one other peer
  • Check that message forwarding is working (watch for your own messages bouncing back)
  • Restart peers with fresh connections

8. High CPU Usage

Problem: Application consuming too much CPU.

Possible Causes:

  • Message loop (deduplication not working)
  • Too many connections
  • Network issues causing constant reconnection attempts

Solutions:

  • Check for duplicate messages (indicates loop)
  • Reduce number of peer connections
  • Monitor connection error messages

Security Considerations

Important Security Notes

This application is designed for trusted LAN environments only. It is intended for educational purposes, local development, or controlled network environments. Do NOT expose this application to the public internet without additional security measures.

Current Limitations

  1. No Authentication: Anyone who can reach the port can join the chat
  2. No Encryption: All messages are sent in plaintext over the network
  3. No Authorization: Any peer can impersonate any user by choosing that name
  4. No Input Validation: Malicious JSON could potentially cause issues
  5. No Rate Limiting: Peers can flood the network with messages
  6. No Message Size Limits: Large messages could consume memory

Recommended Security Practices

If you must use this on a less trusted network:

  1. Use a VPN: Run the chat over a VPN tunnel (e.g., WireGuard, OpenVPN)
  2. Firewall Rules: Restrict port access to known IP addresses:
    sudo ufw allow from 192.168.1.0/24 to any port 5000
  3. SSH Tunneling: Tunnel connections through SSH:
    ssh -L 5000:localhost:5000 user@remote-host
  4. Network Isolation: Use on isolated network segments (VLANs)
  5. Monitoring: Watch logs for suspicious connection patterns

For Production Use

To make this application production-ready, consider adding:

  • TLS/SSL encryption for all connections
  • Authentication tokens or shared secrets
  • Message signing to verify sender identity
  • Input sanitization and validation
  • Rate limiting to prevent abuse
  • Message size limits
  • Access control lists (allow/deny lists)
  • Audit logging of all connections and messages

Privacy Considerations

  • Messages are broadcast to all peers (no private messaging)
  • Connection logs show IP addresses of all peers
  • Message history is not encrypted or protected
  • Timestamps reveal when users are active

Remember: Only use this application in environments where you trust all participants and the network infrastructure.

Contributing

Contributions are welcome! Here's how you can help:

Reporting Issues

If you find a bug or have a feature request:

  1. Check if the issue already exists in the issue tracker
  2. Provide detailed information:
    • Python version
    • Operating system
    • Steps to reproduce
    • Expected vs actual behavior
    • Error messages or logs

Submitting Changes

  1. Fork the repository

  2. Create a feature branch:

    git checkout -b feature/your-feature-name
  3. Make your changes following these guidelines:

    • Maintain the existing code style
    • Add docstrings for new functions/classes
    • Keep changes focused and atomic
    • Test on multiple platforms if possible
  4. Commit with clear messages:

    git commit -m "Add feature: description of what you added"
  5. Push to your fork and submit a pull request

Development Guidelines

  • Code Style: Follow PEP 8 guidelines
  • Documentation: Update docstrings and comments
  • Type Hints: Use type hints for function signatures
  • Testing: Test with multiple peers and connection scenarios
  • Compatibility: Ensure changes work on Python 3.6+

Ideas for Contributions

Here are some features that would be valuable additions:

  • Message history/logging to file
  • Private direct messages between peers
  • Peer discovery via UDP broadcast
  • Basic encryption support
  • GUI interface (tkinter/Qt)
  • File transfer capability
  • Emoji support
  • Message editing/deletion
  • Typing indicators
  • User presence (online/offline status)
  • Configuration file support
  • Docker container
  • Systemd service files
  • Better connection health monitoring
  • Network topology visualization

License

MIT License

Copyright (c) 2026 LAN Mesh Chat Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Additional Resources

Architecture Diagram

Peer Architecture (Each Node):

┌─────────────────────────────────────────┐
│           User Input Thread             │
│         (Main Thread/stdin)             │
└───────────────┬─────────────────────────┘
                │
                ↓
┌─────────────────────────────────────────┐
│         Message Broadcasting            │
│   (Create UUID, Send to all peers)      │
└───────────────┬─────────────────────────┘
                │
        ┌───────┴────────┐
        ↓                ↓
┌──────────────┐  ┌──────────────┐
│ Server Thread│  │Client Threads│
│ (Accepts new │  │(Connect to   │
│ connections) │  │remote peers) │
└──────┬───────┘  └──────┬───────┘
       │                 │
       └────────┬────────┘
                ↓
       ┌──────────────────┐
       │Handler Threads   │
       │(One per peer     │
       │connection)       │
       └────────┬─────────┘
                │
                ↓
       ┌──────────────────┐
       │Message Processing│
       │- Deduplication   │
       │- Display         │
       │- Forwarding      │
       └──────────────────┘

Network Topology Examples

Linear Topology:

Alice ←→ Bob ←→ Charlie ←→ Dave

Messages propagate through intermediate peers.

Star Topology:

      Bob
       ↑
       │
Alice ←┼→ Charlie
       │
       ↓
      Dave

Alice acts as a hub, but other peers can also connect to each other.

Full Mesh Topology (Recommended):

Alice ←→ Bob
  ↕       ↕
Charlie ←→ Dave

Every peer connects to every other peer for maximum redundancy.

Performance Characteristics

  • Latency: ~1-10ms on LAN (depends on network)
  • Throughput: Limited by TCP socket performance (typically 100+ msg/sec)
  • Memory: ~1MB base + ~1KB per connection + ~100 bytes per seen message
  • CPU: Minimal (mostly I/O bound)
  • Scalability: Tested with 10+ peers; performance degrades with 50+ peers due to O(n) forwarding

FAQ

Q: Can I use this over the internet? A: Technically yes, but not recommended without encryption. Consider SSH tunneling or a VPN.

Q: How many peers can connect? A: No hard limit, but performance degrades with many peers due to message forwarding overhead.

Q: Can peers join after the chat has started? A: Yes! Peers can join and leave at any time. They'll see messages sent after they join.

Q: What happens if a peer disconnects? A: The mesh continues to function. Messages route around the disconnected peer.

Q: Is there a message size limit? A: The receive buffer is 4096 bytes, but messages can span multiple receives. Very large messages may cause issues.

Q: Can I see message history from before I joined? A: No, only messages sent after you connect are received.


Enjoy your mesh chat! For questions or issues, please open an issue on the repository.

About

A serverless LAN mesh chat application with optional Tor support

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages