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.
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
- 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
/quitand/peerscommands for easy management - Timestamped Messages: All messages include timestamps for conversation context
- Cross-platform: Works on Linux, macOS, and Windows
- Python 3.6 or higher
- No external dependencies required (uses only Python standard library)
- Clone or download the application:
git clone <repository-url>
cd lan-mesh-chat- Make the script executable (Linux/macOS):
chmod +x lan_mesh_chat.py- Verify Python version:
python3 --versionThat's it! The application uses only Python's standard library, so no pip install is needed.
Terminal 1 (First peer - Alice):
python3 lan_mesh_chat.py --port 5000 --name AliceTerminal 2 (Second peer - Bob, connecting to Alice):
python3 lan_mesh_chat.py --port 5001 --name Bob --peers localhost:5000Now type messages in either terminal and watch them appear in both!
Terminal 1 (Alice):
python3 lan_mesh_chat.py --port 5000 --name AliceTerminal 2 (Bob):
python3 lan_mesh_chat.py --port 5001 --name Bob --peers localhost:5000Terminal 3 (Charlie):
python3 lan_mesh_chat.py --port 5002 --name Charlie --peers localhost:5000,localhost:5001Charlie connects to both Alice and Bob, creating a fully connected mesh. Messages sent by any peer reach all others.
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) |
python3 lan_mesh_chat.py --port 5000 --name AliceAlice starts listening on port 5000, waiting for other peers to connect.
python3 lan_mesh_chat.py --port 5001 --name Bob --peers 192.168.1.100:5000Bob starts on port 5001 and immediately connects to Alice at IP 192.168.1.100.
python3 lan_mesh_chat.py --port 5002 --name Charlie --peers 192.168.1.100:5000,192.168.1.101:5001Charlie connects to multiple peers simultaneously, joining an existing mesh network.
# 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:5000Once 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 |
============================================================
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!
LAN Mesh Chat implements a true peer-to-peer mesh topology:
Alice (5000) ←──────→ Bob (5001)
↑ ↑
│ │
└────→ Charlie ←─────┘
(5002)
Key Concepts:
-
Dual Role: Each peer acts as both a server (accepting connections) and a client (initiating connections)
-
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
-
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
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"
}- Each message gets a unique UUID when created
- Every peer maintains a set of seen message IDs
- 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
- Seen set is capped at 1,000 messages to prevent memory bloat
- 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
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 AliceProblem: 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 firewallSolutions:
- 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.0or specific IP instead oflocalhostfor LAN access
Problem: Peers are connected but messages don't appear.
Solutions:
- Check
/peerscommand to verify connections - Look for error messages in the terminal
- Restart peers in correct order (server peer first)
- Verify network connectivity between machines
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 AliceProblem: Peers on different machines cannot connect.
Solutions:
Linux (UFW):
sudo ufw allow 5000/tcp
sudo ufw reloadLinux (firewalld):
sudo firewall-cmd --add-port=5000/tcp --permanent
sudo firewall-cmd --reloadmacOS:
# Add rule in System Preferences > Security & Privacy > Firewall > Firewall Options
# Or temporarily disable: sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate offWindows:
# Run as Administrator
New-NetFirewallRule -DisplayName "LAN Mesh Chat" -Direction Inbound -Protocol TCP -LocalPort 5000 -Action AllowProblem: 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)Problem: Peers connect but messages don't propagate through the mesh.
Diagnostics:
- Use
/peerscommand 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
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
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.
- No Authentication: Anyone who can reach the port can join the chat
- No Encryption: All messages are sent in plaintext over the network
- No Authorization: Any peer can impersonate any user by choosing that name
- No Input Validation: Malicious JSON could potentially cause issues
- No Rate Limiting: Peers can flood the network with messages
- No Message Size Limits: Large messages could consume memory
If you must use this on a less trusted network:
- Use a VPN: Run the chat over a VPN tunnel (e.g., WireGuard, OpenVPN)
- Firewall Rules: Restrict port access to known IP addresses:
sudo ufw allow from 192.168.1.0/24 to any port 5000
- SSH Tunneling: Tunnel connections through SSH:
ssh -L 5000:localhost:5000 user@remote-host
- Network Isolation: Use on isolated network segments (VLANs)
- Monitoring: Watch logs for suspicious connection patterns
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
- 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.
Contributions are welcome! Here's how you can help:
If you find a bug or have a feature request:
- Check if the issue already exists in the issue tracker
- Provide detailed information:
- Python version
- Operating system
- Steps to reproduce
- Expected vs actual behavior
- Error messages or logs
-
Fork the repository
-
Create a feature branch:
git checkout -b feature/your-feature-name
-
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
-
Commit with clear messages:
git commit -m "Add feature: description of what you added" -
Push to your fork and submit a pull request
- 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+
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
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.
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 │
└──────────────────┘
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.
- 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
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.