smartnetwork/readme.md

184 lines
6.6 KiB
Markdown
Raw Normal View History

2024-04-14 18:02:08 +02:00
# @push.rocks/smartnetwork
2019-04-16 10:21:11 +02:00
network diagnostics
2024-04-14 18:02:08 +02:00
## Install
To install `@push.rocks/smartnetwork`, run the following command in your terminal:
```bash
npm install @push.rocks/smartnetwork --save
```
### Performing a Traceroute
You can perform a hop-by-hop traceroute to measure latency per hop. Falls back to a single-hop stub if the `traceroute` binary is unavailable.
```typescript
const hops = await myNetwork.traceroute('google.com', { maxHops: 10, timeout: 5000 });
hops.forEach(h =>
console.log(`${h.ttl}\t${h.ip}\t${h.rtt === null ? '*' : h.rtt + ' ms'}`),
);
```
2024-04-14 18:02:08 +02:00
This command will download `@push.rocks/smartnetwork` and add it to your project's `package.json` file.
2019-04-16 10:21:11 +02:00
## Usage
2024-04-14 18:02:08 +02:00
In this section, we will dive deep into the capabilities of the `@push.rocks/smartnetwork` package, exploring its various features through TypeScript examples. The package is designed to simplify network diagnostics tasks, including speed tests, port availability checks, ping operations, and more.
### Basic Setup
First, import the package into your project:
```typescript
import { SmartNetwork } from '@push.rocks/smartnetwork';
```
Then, create an instance of `SmartNetwork`:
```typescript
const myNetwork = new SmartNetwork();
```
### Performing a Speed Test
You can measure the network speed using the `getSpeed` method. It supports optional parameters:
- `parallelStreams`: number of concurrent streams (default: 1)
- `duration`: test duration in seconds (default: fixed segments)
2024-04-14 18:02:08 +02:00
```typescript
const speedTest = async () => {
// Default fixed-segment test
let r = await myNetwork.getSpeed();
console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
// Parallel + duration-based test
r = await myNetwork.getSpeed({ parallelStreams: 3, duration: 5 });
console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
2024-04-14 18:02:08 +02:00
};
speedTest();
```
### Checking Port Availability Locally
The `isLocalPortUnused` method allows you to check if a specific port on your local machine is available for use.
```typescript
const checkLocalPort = async (port: number) => {
const isUnused = await myNetwork.isLocalPortUnused(port);
if (isUnused) {
console.log(`Port ${port} is available.`);
} else {
console.log(`Port ${port} is in use.`);
}
};
checkLocalPort(8080); // Example port number
2024-04-14 18:02:08 +02:00
```
### Checking Remote Port Availability
To verify if a port is available on a remote server, use `isRemotePortAvailable`. You can specify target as `"host:port"` or host plus a numeric port.
2024-04-14 18:02:08 +02:00
```typescript
// Using "host:port"
await myNetwork.isRemotePortAvailable('example.com:443');
// Using host + port
await myNetwork.isRemotePortAvailable('example.com', 443);
// UDP is not supported:
try {
await myNetwork.isRemotePortAvailable('example.com', { port: 53, protocol: 'udp' });
} catch (e) {
console.error((e as any).code); // ENOTSUP
}
2024-04-14 18:02:08 +02:00
```
### Using Ping
The `ping` method sends ICMP echo requests and optionally repeats them to collect statistics.
2024-04-14 18:02:08 +02:00
```typescript
// Single ping
const p1 = await myNetwork.ping('google.com');
console.log(`Alive: ${p1.alive}, RTT: ${p1.time} ms`);
// Multiple pings with statistics
const stats = await myNetwork.ping('google.com', { count: 5 });
console.log(
`min=${stats.min} ms, max=${stats.max} ms, avg=${stats.avg.toFixed(2)} ms, loss=${stats.packetLoss}%`,
);
2024-04-14 18:02:08 +02:00
```
### Getting Network Gateways
You can also retrieve network interfaces (gateways) and determine the default gateway. Caching with TTL is supported via constructor options.
2024-04-14 18:02:08 +02:00
2019-04-16 10:21:11 +02:00
```typescript
// Create with cache TTL of 60 seconds
const netCached = new SmartNetwork({ cacheTtl: 60000 });
2019-04-17 20:05:07 +02:00
// List all interfaces
const gateways = await netCached.getGateways();
console.log(gateways);
2021-04-28 13:41:55 +00:00
// Get default gateway
const defaultGw = await netCached.getDefaultGateway();
console.log(defaultGw);
2024-04-14 18:02:08 +02:00
```
2021-04-28 13:41:55 +00:00
2024-04-14 18:02:08 +02:00
### Discovering Public IP Addresses
To find out your public IPv4 and IPv6 addresses (with caching):
2024-04-14 18:02:08 +02:00
```typescript
const publicIps = await netCached.getPublicIps();
console.log(`Public IPv4: ${publicIps.v4}`);
console.log(`Public IPv6: ${publicIps.v6}`);
2019-04-16 10:21:11 +02:00
```
2024-04-14 18:02:08 +02:00
The `@push.rocks/smartnetwork` package provides an easy-to-use, comprehensive suite of tools for network diagnostics and monitoring, encapsulating complex network operations into simple asynchronous methods. By leveraging TypeScript, developers can benefit from type checking, ensuring that they can work with clear structures and expectations.
These examples offer a glimpse into the module's utility in real-world scenarios, demonstrating its versatility in handling common network tasks. Whether you're developing a network-sensitive application, diagnosing connectivity issues, or simply curious about your network performance, `@push.rocks/smartnetwork` equips you with the tools you need.
### Plugin Architecture
You can extend `SmartNetwork` with custom plugins by registering them at runtime:
```typescript
import { SmartNetwork } from '@push.rocks/smartnetwork';
// Define your plugin class or constructor
class MyCustomPlugin {
// plugin implementation goes here
}
// Register and unregister your plugin by name
SmartNetwork.registerPlugin('myPlugin', MyCustomPlugin);
// Later, remove it if no longer needed
SmartNetwork.unregisterPlugin('myPlugin');
```
Plugins enable you to dynamically augment the core functionality without altering the library's source.
2024-04-14 18:02:08 +02:00
## License and Legal Information
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
2024-04-14 18:02:08 +02: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.