9.1 KiB
9.1 KiB
Ejemplos de Uso - API Ping Service
Este documento contiene ejemplos prácticos de cómo usar la API Ping Service en diferentes escenarios.
📡 Ejemplos de API
1. Ping Básico
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{
"target": "8.8.8.8",
"count": 4,
"timeout": 5000
}'
Respuesta:
{
"success": true,
"target": "8.8.8.8",
"timestamp": "2025-08-16T21:00:00.000Z",
"results": [
{
"sequence": 1,
"time": 15.2,
"alive": true,
"host": "8.8.8.8"
}
],
"statistics": {
"packetsTransmitted": 4,
"packetsReceived": 4,
"packetLoss": "0.0",
"min": 14.1,
"max": 16.8,
"avg": "15.20"
}
}
2. Ping a Hostname
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{
"target": "google.com",
"count": 3,
"timeout": 3000
}'
3. Ping Rápido (1 ping)
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{
"target": "1.1.1.1",
"count": 1,
"timeout": 2000
}'
4. Verificar Estado del Servicio
curl -X GET http://localhost:3000/api/status
🚨 Ejemplos de Errores
Rate Limit Excedido
# Después de 5 requests en 10 minutos
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "8.8.8.8"}'
Respuesta (HTTP 429):
{
"error": "Rate limit exceeded",
"message": "Too many requests. Please try again later.",
"resetTime": 1692181260000,
"limit": 5,
"remaining": 0
}
IP Privada (Bloqueada)
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "192.168.1.1"}'
Respuesta (HTTP 400):
{
"error": "Invalid target",
"message": "Private, loopback, or reserved IP addresses are not allowed"
}
Target Inválido
curl -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "invalid..hostname"}'
Respuesta (HTTP 400):
{
"error": "Invalid target",
"message": "Invalid IP address or hostname format"
}
💻 Ejemplos en JavaScript
1. Función de Ping Simple
async function pingHost(target, count = 4) {
try {
const response = await fetch('/api/ping', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
target,
count,
timeout: 5000
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
const result = await response.json();
console.log(`Ping to ${target}:`);
console.log(`Average: ${result.statistics.avg}ms`);
console.log(`Packet Loss: ${result.statistics.packetLoss}%`);
return result;
} catch (error) {
console.error('Ping failed:', error.message);
throw error;
}
}
// Uso
pingHost('8.8.8.8', 3);
2. Monitor de Múltiples Hosts
async function monitorHosts(hosts) {
const results = [];
for (const host of hosts) {
try {
const result = await pingHost(host, 2);
results.push({
host,
success: true,
averageTime: result.statistics.avg,
packetLoss: result.statistics.packetLoss
});
} catch (error) {
results.push({
host,
success: false,
error: error.message
});
}
// Esperar 2 segundos entre hosts para no saturar
await new Promise(resolve => setTimeout(resolve, 2000));
}
return results;
}
// Uso
const hosts = ['8.8.8.8', '1.1.1.1', 'google.com', 'github.com'];
monitorHosts(hosts).then(console.log);
3. Verificador de Rate Limit
async function checkRateLimit() {
try {
const response = await fetch('/api/status');
const data = await response.json();
const rateLimit = data.clientInfo.rateLimit;
console.log(`Rate Limit: ${rateLimit.remaining}/${rateLimit.limit} remaining`);
if (rateLimit.remaining < 2) {
console.warn('⚠️ Approaching rate limit!');
}
return rateLimit;
} catch (error) {
console.error('Failed to check rate limit:', error);
return null;
}
}
4. Ping con Reintentos
async function pingWithRetry(target, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.log(`Attempt ${attempt}/${maxRetries} for ${target}`);
const result = await pingHost(target, 1);
console.log(`✅ Success on attempt ${attempt}`);
return result;
} catch (error) {
console.log(`❌ Attempt ${attempt} failed: ${error.message}`);
if (attempt === maxRetries) {
throw new Error(`Failed after ${maxRetries} attempts: ${error.message}`);
}
// Esperar antes del siguiente intento
const delay = attempt * 1000; // 1s, 2s, 3s...
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
🐍 Ejemplos en Python
1. Cliente Python Simple
import requests
import json
import time
class PingClient:
def __init__(self, base_url="http://localhost:3000"):
self.base_url = base_url
def ping(self, target, count=4, timeout=5000):
"""Realiza un ping al target especificado"""
url = f"{self.base_url}/api/ping"
data = {
"target": target,
"count": count,
"timeout": timeout
}
try:
response = requests.post(url, json=data)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
def get_status(self):
"""Obtiene el estado del servicio"""
url = f"{self.base_url}/api/status"
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
# Uso
client = PingClient()
# Ping simple
result = client.ping("8.8.8.8", count=3)
if result:
print(f"Average: {result['statistics']['avg']}ms")
# Verificar estado
status = client.get_status()
if status:
print(f"Service: {status['service']}")
print(f"Rate limit: {status['clientInfo']['rateLimit']['remaining']}/5")
2. Monitor Continuo
import time
import datetime
def monitor_host(client, target, interval=60, duration=3600):
"""Monitorea un host durante un período específico"""
start_time = time.time()
end_time = start_time + duration
print(f"Monitoring {target} for {duration/60} minutes...")
while time.time() < end_time:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
result = client.ping(target, count=1)
if result and result.get('success'):
avg_time = result['statistics']['avg']
packet_loss = result['statistics']['packetLoss']
print(f"[{timestamp}] {target}: {avg_time}ms (loss: {packet_loss}%)")
else:
print(f"[{timestamp}] {target}: FAILED")
time.sleep(interval)
# Uso
client = PingClient()
monitor_host(client, "8.8.8.8", interval=30, duration=1800) # 30 min
🔧 Headers de Rate Limiting
El servicio incluye headers HTTP para monitorear el rate limiting:
curl -I -X POST http://localhost:3000/api/ping \
-H "Content-Type: application/json" \
-d '{"target": "8.8.8.8"}'
Headers de respuesta:
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 4
X-RateLimit-Reset: 1692181260000
🚀 Casos de Uso Avanzados
Dashboard de Monitoreo
class NetworkDashboard {
constructor() {
this.hosts = ['8.8.8.8', '1.1.1.1', 'google.com'];
this.results = new Map();
}
async updateStatus() {
for (const host of this.hosts) {
try {
const result = await pingHost(host, 1);
this.results.set(host, {
status: 'up',
latency: result.statistics.avg,
lastCheck: new Date()
});
} catch (error) {
this.results.set(host, {
status: 'down',
error: error.message,
lastCheck: new Date()
});
}
}
this.displayResults();
}
displayResults() {
console.clear();
console.log('🌐 Network Status Dashboard');
console.log('=' .repeat(40));
this.results.forEach((result, host) => {
const icon = result.status === 'up' ? '✅' : '❌';
const info = result.status === 'up'
? `${result.latency}ms`
: result.error;
console.log(`${icon} ${host.padEnd(15)} ${info}`);
});
}
start(interval = 30000) {
this.updateStatus();
setInterval(() => this.updateStatus(), interval);
}
}
// Uso
const dashboard = new NetworkDashboard();
dashboard.start(30000); // Actualizar cada 30 segundos
Estos ejemplos muestran cómo integrar el servicio de ping en diferentes aplicaciones y escenarios de uso real.