> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/zwc456baby/ScrcpyForAndroid/llms.txt
> Use this file to discover all available pages before exploring further.

# Network Setup

> Configure Scrcpy for Android for local and public network access

## Network Requirements

Scrcpy for Android requires network connectivity between the controlling device and the target device. Understanding the network architecture helps optimize performance and troubleshoot connection issues.

## Local Network Configuration

For most use cases, both devices should be on the same local network.

### Prerequisites

<Steps>
  <Step title="Enable ADB over Network">
    On the **target device** (the one to be controlled), enable ADB debugging over TCP/IP:

    ```bash theme={null}
    # Using USB ADB first
    adb tcpip 5555
    ```

    This tells the device to listen for ADB connections on port **5555**.
  </Step>

  <Step title="Find Device IP Address">
    Get the target device's local IP address:

    * Go to Settings → About Phone → Status → IP Address
    * Or use: `adb shell ip addr show wlan0`

    Example: `192.168.1.100`
  </Step>

  <Step title="Test Connection">
    From the controlling device, test the connection:

    ```bash theme={null}
    adb connect 192.168.1.100:5555
    adb devices
    ```

    You should see the device listed.
  </Step>
</Steps>

### Network Ports Used

<Note>
  Scrcpy for Android uses the following ports during operation:
</Note>

| Port     | Direction       | Purpose                         | Configurable                |
| -------- | --------------- | ------------------------------- | --------------------------- |
| **5555** | Client → Target | ADB connection                  | Yes (via ADB)               |
| **7007** | Local only      | Server socket on target device  | No                          |
| **7008** | Local only      | Forwarded port on client device | Defined in `Scrcpy.java:36` |

### Port Forwarding Flow

The connection uses ADB's port forwarding mechanism:

```mermaid theme={null}
graph LR
    A[Client App] -->|Connects to| B[127.0.0.1:7008]
    B -->|ADB Forward| C[ADB Daemon]
    C -->|Network| D[Target ADB:5555]
    D -->|Local Forward| E[Server Socket:7007]
    E -->|Accept| F[Server Process]
```

The forwarding is established in `SendCommands.java:109`:

```java theme={null}
adb -s <ip>:<port> forward tcp:7008 tcp:7007
```

## Public Network Access Setup

To access a device over the internet or different networks, additional configuration is required.

<Warning>
  Exposing ADB to the public internet is a security risk. Only use this in controlled environments with proper security measures.
</Warning>

### Method 1: Router Port Forwarding

If the target device is behind a router:

<Steps>
  <Step title="Set Static IP">
    Configure the target device with a static IP on your local network (e.g., `192.168.1.100`).
  </Step>

  <Step title="Configure Router">
    Log into your router's admin panel and add a port forwarding rule:

    * External Port: `5555`
    * Internal IP: `192.168.1.100`
    * Internal Port: `5555`
    * Protocol: `TCP`
  </Step>

  <Step title="Find Public IP">
    Determine your network's public IP address:

    ```bash theme={null}
    curl ifconfig.me
    ```

    Example: `203.0.113.50`
  </Step>

  <Step title="Connect">
    From the client device, connect using the public IP:

    ```
    203.0.113.50:5555
    ```
  </Step>
</Steps>

### Method 2: VPN Tunnel

A more secure approach using a VPN:

<CardGroup cols={2}>
  <Card title="WireGuard" icon="shield">
    Set up a WireGuard VPN server on your network. Both devices join the VPN and communicate via private IPs.

    **Pros:** Encrypted, secure, NAT traversal
  </Card>

  <Card title="Tailscale/ZeroTier" icon="network-wired">
    Use a mesh VPN service for easy peer-to-peer connections without manual configuration.

    **Pros:** No port forwarding needed, cross-platform
  </Card>
</CardGroup>

### Method 3: Reverse SSH Tunnel

If you have access to a public server:

```bash theme={null}
# On target device (using Termux or similar)
ssh -R 5555:localhost:5555 user@your-server.com

# On client device
adb connect your-server.com:5555
```

## Firewall Configuration

### Target Device Firewall

Android doesn't typically have a firewall by default, but if using custom ROMs or security apps:

<Accordion title="Allow ADB port 5555">
  Ensure TCP port 5555 is allowed for incoming connections from your local network or VPN subnet.
</Accordion>

<Accordion title="Allow local server socket">
  Port 7007 only needs to accept local connections (from the ADB daemon), not external traffic.
</Accordion>

### Client Device Firewall

The client device initiates connections, so typically no inbound rules are needed. However:

* Allow outbound TCP to port 5555 on target device
* Allow local binding to port 7008 (ADB forward)

### Router/Network Firewall

If devices are on different subnets within the same network:

1. Allow TCP port 5555 between subnets
2. Consider using VLANs for security isolation
3. Implement access control lists (ACLs) if needed

## Network Performance Tuning

### Bandwidth Requirements

The application's bandwidth usage depends on your configuration:

| Resolution | Bitrate | Estimated Bandwidth |
| ---------- | ------- | ------------------- |
| 1080p      | 2 Mbps  | \~2-3 Mbps total    |
| 1080p      | 4 Mbps  | \~4-5 Mbps total    |
| 1440p      | 8 Mbps  | \~8-10 Mbps total   |

<Info>
  Bandwidth includes video (H.264), audio (AAC at 128kbps), and control data. The bitrate is configurable in the app UI.
</Info>

### Optimizing for Different Networks

<Tabs>
  <Tab title="Local Wi-Fi (Optimal)">
    **Configuration:**

    * Bitrate: 4-8 Mbps
    * Resolution: Native or 1080p
    * Delay tolerance: 50ms

    **Tips:**

    * Use 5GHz Wi-Fi for better bandwidth and lower latency
    * Ensure both devices have strong signal strength
    * Disable Wi-Fi power saving on both devices
  </Tab>

  <Tab title="Mobile Data / 4G">
    **Configuration:**

    * Bitrate: 1-2 Mbps
    * Resolution: 720p or lower
    * Delay tolerance: 100-200ms

    **Tips:**

    * Monitor data usage
    * Use lower frame rates if bandwidth is limited
    * Consider audio-only mode if needed
  </Tab>

  <Tab title="Public Network / VPN">
    **Configuration:**

    * Bitrate: 1-4 Mbps (based on connection)
    * Resolution: 720p-1080p
    * Delay tolerance: 200-500ms

    **Tips:**

    * Adjust bitrate based on available bandwidth
    * Use quality monitoring to detect packet loss
    * Consider TCP optimization for VPN tunnels
  </Tab>
</Tabs>

### Delay Control

The application includes delay tolerance settings to handle network latency (`Scrcpy.java:342-469`):

* **Purpose:** Drops frames that arrive too late to maintain sync
* **Configuration:** Available in app settings (50ms, 100ms, 200ms, etc.)
* **Algorithm:**
  ```java theme={null}
  if (System.currentTimeMillis() - (lastOffset + presentationTimeStamp) < delay) {
      // Render frame
  } else {
      // Drop frame
  }
  ```

<Note>
  Higher delay tolerance = smoother playback but increased latency. Lower values = more responsive but may stutter on slow networks.
</Note>

### Connection Stability

The client implements automatic retry logic (`Scrcpy.java:238-340`):

* **Initial connection:** 50 attempts with 100ms intervals (5 seconds total)
* **Handshake timeout:** 10 attempts × 100ms = 1 second
* **Auto-reconnect:** Available in headless mode

To improve stability:

1. **Reduce packet size:** Lower resolution and bitrate
2. **Enable QoS:** Configure router Quality of Service for ADB traffic
3. **Use wired connection:** If possible, connect target device via USB tethering or Ethernet adapter

## Troubleshooting Network Issues

<AccordionGroup>
  <Accordion title="Connection Timed Out">
    **Symptoms:** "Connection Timed out" error after starting

    **Solutions:**

    * Verify target device IP address is correct
    * Check both devices are on same network (or VPN)
    * Ensure port 5555 is not blocked by firewall
    * Restart ADB on target: `adb kill-server && adb tcpip 5555`
    * Check target device has not gone to sleep (disable battery optimization)
  </Accordion>

  <Accordion title="Laggy or Stuttering Video">
    **Symptoms:** High latency, frame drops, stuttering

    **Solutions:**

    * Lower bitrate setting in app
    * Reduce resolution
    * Increase delay tolerance
    * Move closer to Wi-Fi router
    * Check for network congestion (other devices using bandwidth)
    * Use 5GHz Wi-Fi instead of 2.4GHz
  </Accordion>

  <Accordion title="Disconnects Frequently">
    **Symptoms:** Connection drops after a few minutes

    **Solutions:**

    * Disable battery optimization for ADB and Scrcpy app
    * Keep target device screen on during mirroring
    * Check for Wi-Fi sleep settings
    * Ensure stable network (weak signal causes drops)
    * Enable "Keep Wi-Fi on during sleep" on both devices
  </Accordion>

  <Accordion title="Cannot Connect Over Internet">
    **Symptoms:** Works on local network but not remotely

    **Solutions:**

    * Verify port forwarding is correctly configured
    * Check router firewall allows port 5555
    * Test using public IP (not local 192.168.x.x)
    * Consider using VPN instead of port forwarding
    * Check ISP doesn't block incoming connections (use DMZ as test)
  </Accordion>
</AccordionGroup>

## Security Considerations

<Warning>
  **ADB is not encrypted and has no authentication.** Anyone who can connect to port 5555 has full device access.
</Warning>

### Best Practices

1. **Use VPN:** Always use VPN for remote access instead of exposing port 5555
2. **Disable when not in use:** Turn off ADB network listening when not needed
3. **Whitelist IPs:** Use firewall rules to allow only specific client IPs
4. **Monitor connections:** Check `adb devices` to see what's connected
5. **Use authentication:** Consider ADB key-based authentication (requires initial USB pairing)

### Alternative: ADB Key Authentication

For enhanced security, use ADB key-based authentication:

```bash theme={null}
# Generate ADB keys (done automatically on first connection)
# Keys stored in ~/.android/adbkey and adbkey.pub

# Target device will prompt to "Allow USB debugging" on first connect
# Select "Always allow from this computer"
```

This ensures only authorized devices can connect, even if they know the IP address.
