2025-09-12 13:30:09 +00:00
# @push.rocks/smartnetwork 🌐
2025-04-28 12:58:01 +00:00
2025-07-31 22:04:20 +00:00
Comprehensive network diagnostics and utilities for Node.js applications
2019-04-16 10:21:11 +02:00
2025-09-12 13:30:09 +00:00
## 🚀 Install
2024-04-14 18:02:08 +02:00
To install `@push.rocks/smartnetwork` , run the following command in your terminal:
```bash
2025-09-12 13:30:09 +00:00
pnpm install @push .rocks/smartnetwork --save
2024-04-14 18:02:08 +02:00
```
2025-09-12 13:30:09 +00:00
## 🎯 Overview
2019-04-16 10:21:11 +02:00
2025-09-12 13:30:09 +00:00
**@push .rocks/smartnetwork** is your Swiss Army knife for network diagnostics in Node.js. Whether you're building network monitoring tools, implementing health checks, or just need to debug connectivity issues, this library has you covered with a clean, promise-based API.
### ✨ Key Features
- **🏎️ Speed Testing** - Measure download/upload speeds using Cloudflare's infrastructure
2025-09-12 17:59:06 +00:00
- **🔌 Port Management** - Check local/remote port availability, find free ports (sequential or random)
2025-09-12 13:30:09 +00:00
- **📡 Connectivity Testing** - Ping hosts, trace routes, check endpoints
2025-09-12 17:59:06 +00:00
- **🌍 DNS Operations** - Resolve A, AAAA, and MX records with smart local/remote resolution
2025-09-12 13:30:09 +00:00
- **🔍 Network Discovery** - Get network interfaces, gateways, public IPs
- **⚡ Performance Caching** - Built-in caching for expensive operations
- **🔧 Plugin Architecture** - Extend functionality with custom plugins
- **📝 Full TypeScript Support** - Complete type definitions included
## 💻 Usage
2024-04-14 18:02:08 +02:00
### Basic Setup
2025-09-12 13:30:09 +00:00
First, import and initialize SmartNetwork:
2024-04-14 18:02:08 +02:00
```typescript
import { SmartNetwork } from '@push .rocks/smartnetwork';
2025-09-12 13:30:09 +00:00
// Basic instance
const network = new SmartNetwork();
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
// With caching enabled (60 seconds TTL)
const cachedNetwork = new SmartNetwork({ cacheTtl: 60000 });
2025-07-31 22:04:20 +00:00
```
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
### 🏎️ Network Speed Testing
2025-05-03 18:56:00 +00:00
2025-09-12 13:30:09 +00:00
Measure your network performance using Cloudflare's global infrastructure:
2024-04-14 18:02:08 +02:00
```typescript
const speedTest = async () => {
2025-09-12 13:30:09 +00:00
// Quick speed test
const result = await network.getSpeed();
2025-07-31 22:04:20 +00:00
console.log(`Download: ${result.downloadSpeed} Mbps` );
console.log(`Upload: ${result.uploadSpeed} Mbps` );
2025-09-12 13:30:09 +00:00
// Advanced configuration
const advancedResult = await network.getSpeed({
2025-07-31 22:04:20 +00:00
parallelStreams: 3, // Number of concurrent connections
duration: 5 // Test duration in seconds
});
console.log(`Download: ${advancedResult.downloadSpeed} Mbps` );
console.log(`Upload: ${advancedResult.uploadSpeed} Mbps` );
2024-04-14 18:02:08 +02:00
};
```
2025-09-12 13:30:09 +00:00
### 🔌 Port Management
2025-07-31 22:04:20 +00:00
#### Check Local Port Availability
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
Verify if a port is available on your local machine (checks both IPv4 and IPv6):
2024-04-14 18:02:08 +02:00
```typescript
const checkLocalPort = async (port: number) => {
2025-09-12 13:30:09 +00:00
const isUnused = await network.isLocalPortUnused(port);
2024-04-14 18:02:08 +02:00
if (isUnused) {
2025-09-12 13:30:09 +00:00
console.log(`✅ Port ${port} is available` );
2024-04-14 18:02:08 +02:00
} else {
2025-09-12 13:30:09 +00:00
console.log(`❌ Port ${port} is in use` );
2024-04-14 18:02:08 +02:00
}
};
2025-07-31 22:04:20 +00:00
await checkLocalPort(8080);
```
#### Find Free Port in Range
2025-09-12 13:30:09 +00:00
Automatically discover available ports:
2025-07-31 22:04:20 +00:00
```typescript
const findFreePort = async () => {
2025-09-12 17:59:06 +00:00
// Find a free port between 3000 and 3100 (sequential - returns first available)
2025-09-12 13:30:09 +00:00
const freePort = await network.findFreePort(3000, 3100);
2025-07-31 22:04:20 +00:00
if (freePort) {
2025-09-12 13:30:09 +00:00
console.log(`🎉 Found free port: ${freePort}` );
2025-07-31 22:04:20 +00:00
} else {
2025-09-12 13:30:09 +00:00
console.log('😢 No free ports available in range');
2025-07-31 22:04:20 +00:00
}
2025-09-12 17:59:06 +00:00
// Find a random free port in range (useful to avoid port conflicts)
const randomPort = await network.findFreePort(3000, 3100, { randomize: true });
console.log(`🎲 Random free port: ${randomPort}` );
2025-09-12 18:26:56 +00:00
// Exclude specific ports from the search
const portWithExclusions = await network.findFreePort(3000, 3100, {
exclude: [3000, 3001, 3005] // Skip these ports even if they're free
});
console.log(`🚫 Free port (excluding specific ports): ${portWithExclusions}` );
// Combine randomize with exclude options
const randomWithExclusions = await network.findFreePort(3000, 3100, {
randomize: true,
exclude: [3000, 3001, 3005]
});
console.log(`🎲🚫 Random free port (with exclusions): ${randomWithExclusions}` );
2025-07-31 22:04:20 +00:00
};
2024-04-14 18:02:08 +02:00
```
2025-07-31 22:04:20 +00:00
#### Check Remote Port Availability
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
Test if services are accessible on remote servers:
2024-04-14 18:02:08 +02:00
```typescript
2025-07-31 22:04:20 +00:00
// Method 1: Using "host:port" syntax
2025-09-12 13:30:09 +00:00
const isOpen1 = await network.isRemotePortAvailable('example.com:443');
2025-07-31 22:04:20 +00:00
// Method 2: Using separate host and port
2025-09-12 13:30:09 +00:00
const isOpen2 = await network.isRemotePortAvailable('example.com', 443);
2025-04-28 19:27:13 +00:00
2025-09-12 13:30:09 +00:00
// Method 3: With advanced options
const isOpen3 = await network.isRemotePortAvailable('example.com', {
2025-07-31 22:04:20 +00:00
port: 443,
protocol: 'tcp', // Only TCP is supported
retries: 3, // Number of connection attempts
timeout: 5000 // Timeout per attempt in ms
});
2025-04-28 19:27:13 +00:00
2025-09-12 13:30:09 +00:00
// Note: UDP is not supported
2025-04-28 19:27:13 +00:00
try {
2025-09-12 13:30:09 +00:00
await network.isRemotePortAvailable('example.com', {
2025-07-31 22:04:20 +00:00
port: 53,
protocol: 'udp'
});
2025-04-28 19:27:13 +00:00
} catch (e) {
2025-09-12 13:30:09 +00:00
console.error('UDP not supported:', e.code); // ENOTSUP
2025-04-28 19:27:13 +00:00
}
2024-04-14 18:02:08 +02:00
```
2025-09-12 13:30:09 +00:00
### 📡 Network Connectivity
2025-07-31 22:04:20 +00:00
#### Ping Operations
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
Test connectivity and measure latency:
2024-04-14 18:02:08 +02:00
```typescript
2025-07-31 22:04:20 +00:00
// Simple ping
2025-09-12 13:30:09 +00:00
const pingResult = await network.ping('google.com');
2025-07-31 22:04:20 +00:00
console.log(`Host alive: ${pingResult.alive}` );
console.log(`RTT: ${pingResult.time} ms` );
2025-09-12 13:30:09 +00:00
// Detailed ping statistics
const pingStats = await network.ping('google.com', {
2025-07-31 22:04:20 +00:00
count: 5, // Number of pings
timeout: 1000 // Timeout per ping in ms
});
2025-09-12 13:30:09 +00:00
console.log(`📊 Ping Statistics:` );
console.log(` Packet loss: ${pingStats.packetLoss}%` );
console.log(` Min: ${pingStats.min} ms` );
console.log(` Max: ${pingStats.max} ms` );
console.log(` Avg: ${pingStats.avg.toFixed(2)} ms` );
console.log(` Stddev: ${pingStats.stddev.toFixed(2)} ms` );
2025-07-31 22:04:20 +00:00
```
#### Traceroute
2025-04-28 19:27:13 +00:00
2025-09-12 13:30:09 +00:00
Analyze network paths hop-by-hop:
2025-07-31 22:04:20 +00:00
```typescript
2025-09-12 13:30:09 +00:00
const hops = await network.traceroute('google.com', {
2025-07-31 22:04:20 +00:00
maxHops: 10, // Maximum number of hops
timeout: 5000 // Timeout in ms
});
2025-09-12 13:30:09 +00:00
console.log('🛤️ Route to destination:');
2025-07-31 22:04:20 +00:00
hops.forEach(hop => {
const rtt = hop.rtt === null ? '*' : `${hop.rtt} ms` ;
2025-09-12 13:30:09 +00:00
console.log(` ${hop.ttl}\t${hop.ip}\t${rtt}` );
2025-07-31 22:04:20 +00:00
});
2024-04-14 18:02:08 +02:00
```
2025-09-12 13:30:09 +00:00
*Note: Falls back to a single-hop stub if the `traceroute` binary is unavailable.*
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
### 🌍 DNS Operations
2025-07-31 22:04:20 +00:00
2025-09-12 17:59:06 +00:00
Resolve various DNS record types using @push .rocks/smartdns with intelligent resolution strategy:
2024-04-14 18:02:08 +02:00
2019-04-16 10:21:11 +02:00
```typescript
2025-09-12 13:30:09 +00:00
const dnsRecords = await network.resolveDns('example.com');
2019-04-17 20:05:07 +02:00
2025-09-12 13:30:09 +00:00
console.log('🔍 DNS Records:');
console.log(' A records:', dnsRecords.A); // IPv4 addresses
console.log(' AAAA records:', dnsRecords.AAAA); // IPv6 addresses
2021-04-28 13:41:55 +00:00
2025-07-31 22:04:20 +00:00
// MX records include priority
dnsRecords.MX.forEach(mx => {
2025-09-12 13:30:09 +00:00
console.log(` 📧 Mail server: ${mx.exchange} (priority: ${mx.priority})` );
2025-07-31 22:04:20 +00:00
});
2025-09-12 17:59:06 +00:00
// Properly handles local hostnames (localhost, etc.)
const localDns = await network.resolveDns('localhost');
console.log(' Localhost:', localDns.A); // Returns ['127.0.0.1']
2024-04-14 18:02:08 +02:00
```
2021-04-28 13:41:55 +00:00
2025-09-12 17:59:06 +00:00
*DNS resolution uses a `prefer-system` strategy: tries system resolver first (respects /etc/hosts and local DNS), with automatic fallback to Cloudflare DoH for external domains.*
2025-09-12 13:30:09 +00:00
### 🏥 HTTP/HTTPS Health Checks
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
Monitor endpoint availability and response times:
2024-04-14 18:02:08 +02:00
```typescript
2025-09-12 13:30:09 +00:00
const health = await network.checkEndpoint('https://api.example.com/health', {
2025-07-31 22:04:20 +00:00
timeout: 5000 // Request timeout in ms
});
2025-09-12 13:30:09 +00:00
console.log(`🩺 Endpoint Health:` );
console.log(` Status: ${health.status}` );
console.log(` RTT: ${health.rtt} ms` );
console.log(` Headers:` , health.headers);
2019-04-16 10:21:11 +02:00
```
2025-09-12 13:30:09 +00:00
### 🖥️ Network Interface Information
2024-04-14 18:02:08 +02:00
2025-09-12 13:30:09 +00:00
#### Get All Network Interfaces
2025-05-03 18:56:00 +00:00
2025-09-12 13:30:09 +00:00
List all network adapters on the system:
2025-07-31 22:04:20 +00:00
```typescript
2025-09-12 13:30:09 +00:00
const gateways = await network.getGateways();
2025-07-31 22:04:20 +00:00
Object.entries(gateways).forEach(([name, interfaces]) => {
2025-09-12 13:30:09 +00:00
console.log(`🔌 Interface: ${name}` );
2025-07-31 22:04:20 +00:00
interfaces.forEach(iface => {
console.log(` ${iface.family}: ${iface.address}` );
console.log(` Netmask: ${iface.netmask}` );
console.log(` MAC: ${iface.mac}` );
});
});
```
#### Get Default Gateway
2025-04-28 19:27:13 +00:00
2025-09-12 13:30:09 +00:00
Retrieve the primary network interface:
2025-04-28 19:27:13 +00:00
```typescript
2025-09-12 13:30:09 +00:00
const defaultGateway = await network.getDefaultGateway();
2025-07-31 22:04:20 +00:00
if (defaultGateway) {
2025-09-12 13:30:09 +00:00
console.log('🌐 Default Gateway:');
console.log(' IPv4:', defaultGateway.ipv4.address);
console.log(' IPv6:', defaultGateway.ipv6.address);
2025-07-31 22:04:20 +00:00
}
```
2025-04-28 19:27:13 +00:00
2025-09-12 13:30:09 +00:00
### 🌎 Public IP Discovery
2025-07-31 22:04:20 +00:00
2025-09-12 13:30:09 +00:00
Discover your public-facing IP addresses:
2025-07-31 22:04:20 +00:00
```typescript
2025-09-12 13:30:09 +00:00
const publicIps = await network.getPublicIps();
2025-07-31 22:04:20 +00:00
2025-09-12 13:30:09 +00:00
console.log(`🌍 Public IPs:` );
console.log(` IPv4: ${publicIps.v4 || 'Not available'}` );
console.log(` IPv6: ${publicIps.v6 || 'Not available'}` );
2025-07-31 22:04:20 +00:00
```
2025-09-12 13:30:09 +00:00
### ⚡ Performance Caching
2025-07-31 22:04:20 +00:00
2025-09-12 13:30:09 +00:00
Reduce network calls with built-in caching:
2025-07-31 22:04:20 +00:00
```typescript
// Create instance with 60-second cache TTL
const cachedNetwork = new SmartNetwork({ cacheTtl: 60000 });
2025-09-12 13:30:09 +00:00
// First call fetches from network
2025-07-31 22:04:20 +00:00
const gateways1 = await cachedNetwork.getGateways();
const publicIps1 = await cachedNetwork.getPublicIps();
2025-09-12 13:30:09 +00:00
// Subsequent calls within 60 seconds use cache
const gateways2 = await cachedNetwork.getGateways(); // From cache ⚡
const publicIps2 = await cachedNetwork.getPublicIps(); // From cache ⚡
2025-07-31 22:04:20 +00:00
```
2025-09-12 13:30:09 +00:00
### 🔧 Plugin Architecture
2025-07-31 22:04:20 +00:00
2025-09-12 13:30:09 +00:00
Extend SmartNetwork with custom functionality:
2025-07-31 22:04:20 +00:00
```typescript
// Define your plugin
class CustomNetworkPlugin {
constructor(private smartNetwork: SmartNetwork) {}
async customMethod() {
2025-09-12 13:30:09 +00:00
// Your custom network logic here
return 'Custom result';
2025-07-31 22:04:20 +00:00
}
2025-04-28 19:27:13 +00:00
}
2025-07-31 22:04:20 +00:00
// Register the plugin
SmartNetwork.registerPlugin('customPlugin', CustomNetworkPlugin);
// Use the plugin
const network = new SmartNetwork();
2025-09-12 13:30:09 +00:00
const PluginClass = SmartNetwork.pluginsRegistry.get('customPlugin');
const plugin = new PluginClass(network);
2025-07-31 22:04:20 +00:00
await plugin.customMethod();
2025-09-12 13:30:09 +00:00
// Clean up when done
2025-07-31 22:04:20 +00:00
SmartNetwork.unregisterPlugin('customPlugin');
```
2025-09-12 13:30:09 +00:00
### 🚨 Error Handling
2025-07-31 22:04:20 +00:00
2025-09-12 13:30:09 +00:00
Handle network errors gracefully with custom error types:
2025-07-31 22:04:20 +00:00
```typescript
import { NetworkError } from '@push .rocks/smartnetwork';
try {
2025-09-12 13:30:09 +00:00
await network.isRemotePortAvailable('example.com', { protocol: 'udp' });
2025-07-31 22:04:20 +00:00
} catch (error) {
if (error instanceof NetworkError) {
2025-09-12 13:30:09 +00:00
console.error(`❌ Network error: ${error.message}` );
console.error(` Error code: ${error.code}` );
2025-07-31 22:04:20 +00:00
}
}
2025-04-28 19:27:13 +00:00
```
2025-09-12 13:30:09 +00:00
### 📚 TypeScript Support
2025-07-31 22:04:20 +00:00
2025-09-12 13:30:09 +00:00
This package is written in TypeScript and provides comprehensive type definitions:
2025-07-31 22:04:20 +00:00
```typescript
interface SmartNetworkOptions {
cacheTtl?: number; // Cache TTL in milliseconds
}
2025-09-12 17:59:06 +00:00
interface IFindFreePortOptions {
randomize?: boolean; // If true, returns a random free port instead of the first one
2025-09-12 18:26:56 +00:00
exclude?: number[]; // Array of port numbers to exclude from the search
2025-09-12 17:59:06 +00:00
}
2025-07-31 22:04:20 +00:00
interface Hop {
ttl: number; // Time to live
ip: string; // IP address of the hop
rtt: number | null; // Round trip time in ms
}
2025-09-12 13:30:09 +00:00
// ... and many more types for complete type safety
```
## 🛠️ Advanced Examples
### Building a Network Monitor
```typescript
const monitorNetwork = async () => {
const network = new SmartNetwork({ cacheTtl: 30000 });
// Check critical services
const services = [
{ name: 'Web Server', host: 'example.com', port: 443 },
{ name: 'Database', host: 'db.internal', port: 5432 },
{ name: 'Cache', host: 'redis.internal', port: 6379 }
];
for (const service of services) {
const isUp = await network.isRemotePortAvailable(service.host, service.port);
console.log(`${service.name}: ${isUp ? '✅ UP' : '❌ DOWN'}` );
}
// Check internet connectivity
const ping = await network.ping('8.8.8.8');
console.log(`Internet: ${ping.alive ? '✅ Connected' : '❌ Disconnected'}` );
// Measure network performance
const speed = await network.getSpeed();
console.log(`Speed: ⬇️ ${speed.downloadSpeed} Mbps / ⬆️ ${speed.uploadSpeed} Mbps` );
};
// Run monitor every minute
setInterval(monitorNetwork, 60000);
```
### Service Discovery
```typescript
const discoverServices = async () => {
const network = new SmartNetwork();
const commonPorts = [22, 80, 443, 3000, 3306, 5432, 6379, 8080, 9200];
console.log('🔍 Scanning local services...');
for (const port of commonPorts) {
const isUsed = !(await network.isLocalPortUnused(port));
if (isUsed) {
console.log(` Port ${port}: In use (possible service running)` );
}
}
};
2025-07-31 22:04:20 +00:00
```
2024-04-14 18:02:08 +02:00
## License and Legal Information
2025-07-31 22:04:20 +00:00
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license ](license ) file within this repository.
2024-04-14 18:02:08 +02:00
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
2019-11-19 23:00:37 +00:00
2024-04-14 18:02:08 +02:00
### Company Information
2019-11-19 23:00:37 +00:00
2024-04-14 18:02:08 +02:00
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
2019-04-16 10:21:11 +02:00
2024-04-14 18:02:08 +02:00
For any legal inquiries or if you require further information, please contact us via email at hello@task .vc.
2019-04-16 10:21:11 +02:00
2025-07-31 22:04:20 +00:00
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.