# net_peerCount - TRON RPC Method

Returns the number of peers currently connected to your TRON node.

> **Why TRON?** Build on the TVM-compatible Layer 1 for TRC-20 payments, wallet APIs, and low-cost smart contract execution with TVM compatibility paired with native TRON wallet APIs, DPoS block production, and low-cost transaction flows.

## When to Use This Method

`net_peerCount` is important for TRON developers building payment rails, exchanges, and consumer crypto applications:

- **Network Health Monitoring** - Verify your node has sufficient peer connections for reliable data propagation
- **Peer Discovery Verification** - Confirm that peer discovery is working after node startup or network changes
- **Load Balancer Decisions** - Route traffic to well-connected nodes with healthy peer counts
- **Troubleshooting Connectivity** - Diagnose networking issues when a node returns stale or missing data

## Best Practices

- Low peer count may indicate connectivity or firewall issues; investigate if peers drop unexpectedly
- Minimum healthy peer count varies by network; establish baselines for your specific TRON deployment
- Combine with `eth_syncing` for a complete picture of node health and readiness

## Request Parameters

This method accepts no parameters.

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "net_peerCount",
  "params": [],
  "id": 1
}
```

## Response Fields

- `result` (`QUANTITY, required`): Hexadecimal string representing the number of connected peers

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x19"
}
```

## Error Responses

### Error Response

- Code: `-32601`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32601,
    "message": "The method net_peerCount does not exist/is not available"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Go

```bash
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "net_peerCount",
    "params": [],
    "id": 1
  }'
```

```javascript
import { JsonRpcProvider } from 'ethers';

const provider = new JsonRpcProvider('https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc');

const peerCountHex = await provider.send('net_peerCount', []);
const peerCount = parseInt(peerCountHex, 16);
console.log(`TRON peers: ${peerCount}`);

// Using fetch
const response = await fetch('https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    method: 'net_peerCount',
    params: [],
    id: 1
  })
});

const { result } = await response.json();
console.log('Peers:', parseInt(result, 16));
```

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc'))

peer_count = w3.net.peer_count
print(f'TRON peers: {peer_count}')

# Using requests directly
import requests

response = requests.post(
    'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc',
    json={
        'jsonrpc': '2.0',
        'method': 'net_peerCount',
        'params': [],
        'id': 1
    }
)
result = response.json()['result']
print(f'Peers: {int(result, 16)}')
```

```go
package main

import (
    "context"
    "fmt"
    "log"
    "math/big"

    "github.com/ethereum/go-ethereum/rpc"
)

func main() {
    client, err := rpc.Dial("https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc")
    if err != nil {
        log.Fatal(err)
    }

    var result string
    err = client.CallContext(context.Background(), &result, "net_peerCount")
    if err != nil {
        log.Fatal(err)
    }

    peerCount := new(big.Int)
    peerCount.SetString(result[2:], 16)
    fmt.Printf("TRON peers: %s\n", peerCount.String())
}
```

## Common Use Cases

### 1. Network Health Monitor

Continuously check peer count and alert when it drops below a threshold:

```javascript
async function monitorPeers(provider, minPeers = 3, interval = 30000) {
  setInterval(async () => {
    const peerCountHex = await provider.send('net_peerCount', []);
    const peerCount = parseInt(peerCountHex, 16);

    if (peerCount === 0) {
      console.error('CRITICAL: Node has no peers - network isolated');
    } else if (peerCount < minPeers) {
      console.warn(`LOW PEERS: ${peerCount} connected (minimum: ${minPeers})`);
    } else {
      console.log(`Healthy - ${peerCount} peers connected`);
    }
  }, interval);
}
```

### 2. Node Readiness Check

Verify a node has enough peers before routing traffic to it:

```javascript
async function isNodeReady(rpcUrl, minPeers = 5) {
  const provider = new JsonRpcProvider(rpcUrl);

  const [peerCountHex, syncing] = await Promise.all([
    provider.send('net_peerCount', []),
    provider.send('eth_syncing', [])
  ]);

  const peerCount = parseInt(peerCountHex, 16);
  const isSynced = syncing === false;
  const hasEnoughPeers = peerCount >= minPeers;

  return {
    ready: isSynced && hasEnoughPeers,
    peerCount,
    syncing: !isSynced
  };
}
```

### 3. Multi-Node Fleet Dashboard

Aggregate peer counts across a fleet of TRON nodes:

```python
import requests

def check_fleet_peers(endpoints):
    results = []
    for endpoint in endpoints:
        try:
            response = requests.post(
                endpoint,
                json={'jsonrpc': '2.0', 'method': 'net_peerCount', 'params': [], 'id': 1},
                timeout=5
            )
            peers = int(response.json()['result'], 16)
            results.append({'endpoint': endpoint, 'peers': peers, 'healthy': peers > 0})
        except Exception as e:
            results.append({'endpoint': endpoint, 'peers': 0, 'healthy': False, 'error': str(e)})
    return results
```

## Related Methods

- [`net_listening`](https://www.dwellir.com/docs/tron/net_listening) - Check if node is accepting connections
- [`net_version`](https://www.dwellir.com/docs/tron/net_version) - Get the network ID
- [`eth_syncing`](https://www.dwellir.com/docs/tron/eth_syncing) - Check node sync progress
- [`web3_clientVersion`](https://www.dwellir.com/docs/tron/web3_clientVersion) - Get node client info
