Skip to main content

Overview

When running APITHON in Gateway mode, you must choose between two network scopes:
  • Localhost (L) - API accessible only from the host machine (127.0.0.1)
  • LAN (N) - API accessible from any device on your local network (0.0.0.0)
This configuration determines the Flask server’s bind address and affects security, accessibility, and firewall considerations.
Network configuration only applies to Gateway Mode. Chat Mode runs locally without network exposure.

Network Selection Menu

After choosing Gateway Mode (Option 1), you’ll see the network configuration prompt:
[ Configuración de Red ]
L. Localhost (Solo este equipo)
N. LAN (Disponible en toda tu red local)
> Alcance (L/N):
Source Reference: apithon.py:195-208

Input Validation

The selection loop validates your input and repeats until you enter a valid option:
while True:
    print("\n[ Configuración de Red ]")
    print("L. Localhost (Solo este equipo)")
    print("N. LAN (Disponible en toda tu red local)")
    red_opcion = input("> Alcance (L/N): ").upper()
    
    if red_opcion == "L":
        threading.Thread(target=run_gateway_service, args=(False,), daemon=True).start()
        break
    elif red_opcion == "N":
        threading.Thread(target=run_gateway_service, args=(True,), daemon=True).start()
        break
    else:
        print("[!] Ingrese L o N.")
Source Reference: apithon.py:195-208

Localhost Mode (L)

How It Works

When you select L, APITHON starts the Flask server bound to the loopback interface:
def run_gateway_service(bind_all=False):
    host = "0.0.0.0" if bind_all else "127.0.0.1"
    display_ip = get_lan_ip() if bind_all else "127.0.0.1"
    mostrar_tutorial(display_ip)
    app.run(host=host, port=5000, debug=False, use_reloader=False)
With bind_all=False:
  • host = "127.0.0.1"
  • display_ip = "127.0.0.1"
Source Reference: apithon.py:163-167

Use Cases

Personal Development

Testing scripts and automation tools on the same machine

Maximum Security

No network exposure - impossible to access remotely

No Firewall Issues

Bypasses all firewall rules since traffic never leaves the host

Single-User Workflows

When you only need to run queries from the host machine

Example Commands

The tutorial displays commands using 127.0.0.1:
curl http://127.0.0.1:5000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer UnHackerEnCapital' \
  -d '{"messages": [{"role": "user", "content": "Test query"}]}'
Access RestrictionsAttempting to access http://<your-lan-ip>:5000 from another device will fail with a connection timeout or “Connection refused” error because the server isn’t listening on the network interface.

LAN Mode (N)

How It Works

When you select N, APITHON binds to all network interfaces and detects your LAN IP:
def run_gateway_service(bind_all=False):
    host = "0.0.0.0" if bind_all else "127.0.0.1"
    display_ip = get_lan_ip() if bind_all else "127.0.0.1"
    mostrar_tutorial(display_ip)
    app.run(host=host, port=5000, debug=False, use_reloader=False)
With bind_all=True:
  • host = "0.0.0.0" - Listens on all network interfaces
  • display_ip = get_lan_ip() - Detects and displays your private IP
Source Reference: apithon.py:163-167

IP Detection Mechanism

APITHON automatically discovers your LAN IP address:
def get_lan_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception:
        return "127.0.0.1"
How it works:
  1. Creates a UDP socket (no actual data transmitted)
  2. “Connects” to Google’s DNS server (8.8.8.8:80)
  3. Retrieves the local socket address used for routing
  4. Returns the IP address, or falls back to 127.0.0.1 on failure
Source Reference: apithon.py:43-51
Why 8.8.8.8?This technique uses Google’s public DNS as a routing target to determine which network interface the system would use for internet connectivity. No packets are actually sent - it’s just a trick to query the kernel’s routing table.

Use Cases

Multi-Device Access

Access the API from phones, tablets, or other computers on your network

Team Collaboration

Multiple users in the same office/home can share one gateway instance

IoT Integration

Connect embedded devices or smart home systems to the API

Testing Distributed Systems

Test how different services interact with the API across the network

Example Commands

The tutorial displays commands using your detected LAN IP (e.g., 192.168.1.45):
curl http://192.168.1.45:5000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer UnHackerEnCapital' \
  -d '{"messages": [{"role": "user", "content": "Test from another device"}]}'
Testing LAN AccessFrom another device on your network:
  1. Note the IP displayed in the APITHON tutorial (e.g., 192.168.1.45)
  2. Use that IP in place of localhost or 127.0.0.1
  3. Ensure both devices are on the same subnet
  4. Verify firewall rules allow incoming connections on port 5000

Security Considerations

LAN Mode Exposes Your GatewayWhen running in LAN mode, any device on your network can send requests to your API gateway if they know:
  • Your LAN IP address
  • The port (5000)
  • The API key (UnHackerEnCapital by default)

Authentication

APITHON implements basic Bearer token authentication:
@app.route('/v1/chat/completions', methods=['POST'])
def apithon_gateway():
    auth_header = request.headers.get("Authorization")
    if auth_header != f"Bearer {API_KEY_GATEWAY}":
        return jsonify({"error": "Unauthorized"}), 401
    # ... rest of the function
Default API Key: UnHackerEnCapital (defined at apithon.py:29)
Changing the API KeyEdit line 29 of apithon.py to set a custom API key:
API_KEY_GATEWAY = "your-custom-secure-key-here"
Restart APITHON for changes to take effect.

Best Practices

  • Change the default API key before deploying in LAN mode
  • Use a randomly generated string with high entropy
  • Consider using environment variables: API_KEY_GATEWAY = os.getenv("APITHON_KEY", "fallback")
  • Only use LAN mode on trusted networks (home/office)
  • Avoid using LAN mode on public WiFi or shared networks
  • Consider using a separate VLAN for security testing tools
  • Monitor Flask logs for unexpected API calls
  • Implement request logging to track who’s accessing the gateway
  • Consider adding IP whitelisting for production use
  • Don’t leave the gateway running indefinitely
  • Use Ctrl+C to properly shut down when finished
  • Remember: the session data remains in memory while running

Firewall Configuration

Port Requirements

APITHON uses port 5000 for the Flask server (hardcoded in apithon.py:167).

Windows Firewall

If you’re running in LAN mode on Windows and other devices can’t connect:
1

Open Windows Defender Firewall

Search for “Windows Defender Firewall” in the Start menu
2

Click Advanced Settings

Select “Advanced settings” in the left sidebar
3

Create Inbound Rule

  1. Right-click “Inbound Rules” → “New Rule”
  2. Select “Port” → Next
  3. Select “TCP” and enter “5000” → Next
  4. Select “Allow the connection” → Next
  5. Check all profiles (Domain, Private, Public) → Next
  6. Name it “APITHON Gateway” → Finish

Linux Firewall (UFW)

# Allow port 5000 from local network only
sudo ufw allow from 192.168.1.0/24 to any port 5000

# Or allow from anywhere (less secure)
sudo ufw allow 5000/tcp

# Check status
sudo ufw status

Linux Firewall (firewalld)

# Add port 5000 to the firewall
sudo firewall-cmd --zone=public --add-port=5000/tcp --permanent

# Reload firewall
sudo firewall-cmd --reload

# Verify
sudo firewall-cmd --list-ports
macOS UsersmacOS typically doesn’t block incoming connections by default, but if you have Application Firewall enabled:
  1. System Preferences → Security & Privacy → Firewall
  2. Click “Firewall Options”
  3. Ensure Python is allowed to accept incoming connections

Network Topology Examples

Localhost Architecture

┌─────────────────────────────────────┐
│     Host Machine (127.0.0.1)        │
│                                     │
│  ┌──────────┐      ┌─────────────┐ │
│  │  APITHON │◄────►│  Your Tools │ │
│  │  Gateway │      │   (Python,  │ │
│  │ Port 5000│      │    curl, etc)│ │
│  └──────────┘      └─────────────┘ │
│                                     │
│  Traffic never leaves this machine  │
└─────────────────────────────────────┘

LAN Architecture

┌─────────────────────────────────────────────────────────┐
│              Local Network (192.168.1.0/24)             │
│                                                         │
│  ┌──────────────────────┐      ┌──────────────────┐   │
│  │  Host Machine        │      │  Laptop          │   │
│  │  (192.168.1.45)      │      │  (192.168.1.67)  │   │
│  │                      │      │                  │   │
│  │  ┌────────────────┐  │      │  Sends requests  │   │
│  │  │ APITHON Gateway│◄─┼──────┼──to 192.168.1.45 │   │
│  │  │   Port 5000    │  │      │  :5000           │   │
│  │  └────────────────┘  │      └──────────────────┘   │
│  └──────────────────────┘                             │
│                                                         │
│  ┌──────────────────┐       ┌──────────────────┐      │
│  │  Phone           │       │  IoT Device      │      │
│  │  (192.168.1.89)  │       │  (192.168.1.110) │      │
│  │                  │       │                  │      │
│  │  Can also access │       │  Can also access │      │
│  │  the gateway     │       │  the gateway     │      │
│  └──────────────────┘       └──────────────────┘      │
└─────────────────────────────────────────────────────────┘

Troubleshooting Connection Issues

Checklist:
  1. Verify you selected ‘N’ (LAN mode)
    • If you selected ‘L’ by mistake, restart and choose ‘N’
  2. Confirm both devices are on the same network
    # On host machine
    ip addr show  # Linux
    ipconfig      # Windows
    
    # On client device
    # Compare network prefix (e.g., 192.168.1.x)
    
  3. Check firewall rules (see Firewall Configuration section above)
  4. Verify the gateway is running
    # On another terminal on the host
    netstat -tuln | grep 5000
    # Should show: tcp 0 0 0.0.0.0:5000 0.0.0.0:* LISTEN
    
  5. Test with curl from the client device
    # Replace <HOST_IP> with the IP shown in APITHON tutorial
    curl http://<HOST_IP>:5000/v1/chat/completions \
      -H 'Authorization: Bearer UnHackerEnCapital' \
      -H 'Content-Type: application/json' \
      -d '{"messages": [{"role": "user", "content": "test"}]}'
    
This indicates a firewall issue on the host machine.Quick test:
# On the host machine, test with its LAN IP (not 127.0.0.1)
curl http://192.168.1.45:5000/v1/chat/completions \
  -H 'Authorization: Bearer UnHackerEnCapital' \
  -H 'Content-Type: application/json' \
  -d '{"messages": [{"role": "user", "content": "test"}]}'
If this fails, your firewall is blocking loopback connections. If this succeeds, the firewall is only blocking external connections.→ Follow the Firewall Configuration section to open port 5000.
If get_lan_ip() returns 127.0.0.1 or an unexpected address:Cause: Multiple network interfaces or no default route to internetSolution:
# Manually find your LAN IP
ip addr show        # Linux
ipconfig            # Windows
ifconfig            # macOS

# Look for addresses in these ranges:
# 192.168.x.x (most common)
# 10.x.x.x
# 172.16.x.x - 172.31.x.x
Use the correct IP when accessing from other devices, even if the tutorial shows the wrong one.
Error message: Address already in useSolution:
# Find what's using port 5000
# Linux/macOS
sudo lsof -i :5000

# Windows
netstat -ano | findstr :5000

# Kill the process or change APITHON's port
# Edit apithon.py line 167:
app.run(host=host, port=8080, debug=False, use_reloader=False)

Performance Considerations

Localhost vs LAN Latency

Localhost

  • Latency: Less than 1ms (loopback interface)
  • Bandwidth: Virtually unlimited (no physical network)
  • Reliability: 100% (no network interference)

LAN

  • Latency: 1-5ms (typical home WiFi)
  • Bandwidth: Limited by network speed (WiFi ~100-1000 Mbps)
  • Reliability: Can be affected by network congestion

Flask Threading Model

Flask’s development server (used in APITHON) handles requests sequentially by default:
app.run(host=host, port=5000, debug=False, use_reloader=False)
Implication: If one request takes 10 seconds to complete, subsequent requests will queue.
For Production UseConsider using a production WSGI server for concurrent request handling:
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 apithon:app
This runs 4 worker processes that can handle requests in parallel.

Summary

AspectLocalhost (L)LAN (N)
Bind Address127.0.0.10.0.0.0
AccessibilityHost machine onlyAll devices on network
SecurityMaximum (no network exposure)Moderate (requires API key)
FirewallNo configuration neededMay require firewall rules
IP DetectionStatic 127.0.0.1Dynamic via get_lan_ip()
Use CasePersonal developmentMulti-device access
Tutorial IPAlways 127.0.0.1Detected LAN IP (e.g., 192.168.1.45)
Recommendation
  • Development/Testing: Use Localhost (L) for maximum security and simplicity
  • Team Collaboration: Use LAN (N) when multiple devices need access
  • Always change the default API key in production scenarios

Build docs developers (and LLMs) love