Chamada de Sistema
Ping com Regex
Comando Ping:
$ ping 8.8.8.8 -c 3
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=54 time=82.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=54 time=82.2 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=54 time=84.1 ms
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 82.194/83.019/84.095/0.796 ms
$ ping 8.8.8.8 -c 3
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=54 time=82.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=54 time=82.2 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=54 time=84.1 ms
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 82.194/83.019/84.095/0.796 ms
// ip
/\(([\d\.]+)\)/
//packets
/icmp_seq=(?<seq>\d+) ttl=(?<ttl>\d+) time=(?<time>[\d\.]+)/g
// statistics
/(?<transmitted>\d+) packets transmitted, (?<received>\d+) (packets received|received)/
/min\/avg\/max\/(stddev|mdev) = (?<min>[\d.]+)\/(?<avg>[\d.]+)\/(?<max>[\d.]+)\/(?<stddev>[\d.]+)/
// ip
/\(([\d\.]+)\)/
//packets
/icmp_seq=(?<seq>\d+) ttl=(?<ttl>\d+) time=(?<time>[\d\.]+)/g
// statistics
/(?<transmitted>\d+) packets transmitted, (?<received>\d+) (packets received|received)/
/min\/avg\/max\/(stddev|mdev) = (?<min>[\d.]+)\/(?<avg>[\d.]+)\/(?<max>[\d.]+)\/(?<stddev>[\d.]+)/
Ping API:
Arquivos
ping-command
├── package-lock.json
├── package.json
├── requests.http
└── src
├── index.js
└── lib
└── ping.js
Arquivos
ping-command
├── package-lock.json
├── package.json
├── requests.http
└── src
├── index.js
└── lib
└── ping.js
/codes/expressjs/system-call/ping-command/src/lib/ping.js
import util from 'node:util';
import { exec } from 'node:child_process';
const execAsync = util.promisify(exec);
export async function ping(host, count = 3) {
try {
const command = `ping -c ${count} ${host}`;
const { stdout } = await execAsync(command);
const ping = { host, ...parse(stdout) };
return ping;
} catch (error) {
throw new Error('Unknown host');
}
}
export function parse(output) {
const ping = { output };
// ip
let regex = /\(([\d\.]+)\)/;
let match = output.match(regex);
ping.ip = match[1];
// packets
ping.packets = [];
regex = /icmp_seq=(?<seq>\d+) ttl=(?<ttl>\d+) time=(?<time>[\d\.]+)/g;
while ((match = regex.exec(output))) {
const {
groups: { seq, ttl, time },
} = match;
ping.packets.push({
seq: parseInt(seq),
ttl: parseInt(ttl),
time: parseFloat(time),
});
}
// statistics
regex =
/(?<transmitted>\d+) packets transmitted, (?<received>\d+) (packets received|received)/;
const {
groups: { transmitted, received },
} = output.match(regex);
const losted = transmitted - received;
regex =
/min\/avg\/max\/(stddev|mdev) = (?<min>[\d.]+)\/(?<avg>[\d.]+)\/(?<max>[\d.]+)\/(?<stddev>[\d.]+)/;
const {
groups: { min, avg, max, stddev },
} = output.match(regex);
ping.statistics = {
transmitted: parseInt(transmitted),
received: parseInt(transmitted),
losted: losted,
min: parseFloat(min),
avg: parseFloat(avg),
max: parseFloat(max),
stddev: parseFloat(stddev),
};
return ping;
}
/codes/expressjs/system-call/ping-command/src/lib/ping.js
import util from 'node:util';
import { exec } from 'node:child_process';
const execAsync = util.promisify(exec);
export async function ping(host, count = 3) {
try {
const command = `ping -c ${count} ${host}`;
const { stdout } = await execAsync(command);
const ping = { host, ...parse(stdout) };
return ping;
} catch (error) {
throw new Error('Unknown host');
}
}
export function parse(output) {
const ping = { output };
// ip
let regex = /\(([\d\.]+)\)/;
let match = output.match(regex);
ping.ip = match[1];
// packets
ping.packets = [];
regex = /icmp_seq=(?<seq>\d+) ttl=(?<ttl>\d+) time=(?<time>[\d\.]+)/g;
while ((match = regex.exec(output))) {
const {
groups: { seq, ttl, time },
} = match;
ping.packets.push({
seq: parseInt(seq),
ttl: parseInt(ttl),
time: parseFloat(time),
});
}
// statistics
regex =
/(?<transmitted>\d+) packets transmitted, (?<received>\d+) (packets received|received)/;
const {
groups: { transmitted, received },
} = output.match(regex);
const losted = transmitted - received;
regex =
/min\/avg\/max\/(stddev|mdev) = (?<min>[\d.]+)\/(?<avg>[\d.]+)\/(?<max>[\d.]+)\/(?<stddev>[\d.]+)/;
const {
groups: { min, avg, max, stddev },
} = output.match(regex);
ping.statistics = {
transmitted: parseInt(transmitted),
received: parseInt(transmitted),
losted: losted,
min: parseFloat(min),
avg: parseFloat(avg),
max: parseFloat(max),
stddev: parseFloat(stddev),
};
return ping;
}
/codes/expressjs/system-call/ping-command/src/index.js
import 'express-async-errors';
import express from 'express';
import morgan from 'morgan';
import { ping as requestPing } from './lib/ping.js';
const app = express();
app.use(morgan('tiny'));
app.use(express.json());
class HTTPError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
app.post('/ping', async (req, res) => {
const { host } = req.query;
if (!host) {
throw new HTTPError('Error when passing parameters', 400);
}
try {
const ping = await requestPing(host);
res.json(ping);
} catch (error) {
throw new HTTPError(error.message, 400);
}
});
// 404 handler
app.use((req, res, next) => {
res.status(404).json({ message: 'Content not found!' });
});
// Error handler
app.use((err, req, res, next) => {
if (err instanceof HTTPError) {
return res.status(err.code).json({ message: err.message });
}
// console.error(err.stack);
// next(err)
return res.status(500).json({ message: 'Something broke!' });
});
app.listen(3000, () => {
console.log('App running at http://localhost:3000');
});
/codes/expressjs/system-call/ping-command/src/index.js
import 'express-async-errors';
import express from 'express';
import morgan from 'morgan';
import { ping as requestPing } from './lib/ping.js';
const app = express();
app.use(morgan('tiny'));
app.use(express.json());
class HTTPError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
app.post('/ping', async (req, res) => {
const { host } = req.query;
if (!host) {
throw new HTTPError('Error when passing parameters', 400);
}
try {
const ping = await requestPing(host);
res.json(ping);
} catch (error) {
throw new HTTPError(error.message, 400);
}
});
// 404 handler
app.use((req, res, next) => {
res.status(404).json({ message: 'Content not found!' });
});
// Error handler
app.use((err, req, res, next) => {
if (err instanceof HTTPError) {
return res.status(err.code).json({ message: err.message });
}
// console.error(err.stack);
// next(err)
return res.status(500).json({ message: 'Something broke!' });
});
app.listen(3000, () => {
console.log('App running at http://localhost:3000');
});
/codes/expressjs/system-call/ping-command/requests.http
@server=http://localhost:3000
### Post Ping (with params)
POST {{server}}/ping?host=8.8.8.8
### Post Ping (bad params)
POST {{server}}/ping?host=a.a.a.a
### Post Ping (without params)
POST {{server}}/ping
/codes/expressjs/system-call/ping-command/requests.http
@server=http://localhost:3000
### Post Ping (with params)
POST {{server}}/ping?host=8.8.8.8
### Post Ping (bad params)
POST {{server}}/ping?host=a.a.a.a
### Post Ping (without params)
POST {{server}}/ping
Ping Package
$ npm i ping
$ npm i ping
Ping API:
Arquivos
ping-package
├── package-lock.json
├── package.json
├── requests.http
└── src
└── index.js
Arquivos
ping-package
├── package-lock.json
├── package.json
├── requests.http
└── src
└── index.js
/codes/expressjs/system-call/ping-package/src/index.js
import 'express-async-errors';
import express from 'express';
import morgan from 'morgan';
import ping from 'ping';
const app = express();
app.use(morgan('tiny'));
app.use(express.json());
class HTTPError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
app.post('/ping', async (req, res) => {
const { host } = req.query;
if (!host) {
throw new HTTPError('Error when passing parameters', 400);
}
try {
const pingResult = await ping.promise.probe(host);
if (
['Name or service not known', 'Unknown host'].some((msg) =>
pingResult.output.includes(msg)
)
) {
throw new Error('Unknown host');
}
res.json(pingResult);
} catch (error) {
throw new HTTPError(error.message, 400);
}
});
// 404 handler
app.use((req, res, next) => {
res.status(404).json({ message: 'Content not found!' });
});
// Error handler
app.use((err, req, res, next) => {
if (err instanceof HTTPError) {
return res.status(err.code).json({ message: err.message });
}
// console.error(err.stack);
// next(err)
return res.status(500).json({ message: 'Something broke!' });
});
app.listen(3000, () => {
console.log('App running at http://localhost:3000');
});
/codes/expressjs/system-call/ping-package/src/index.js
import 'express-async-errors';
import express from 'express';
import morgan from 'morgan';
import ping from 'ping';
const app = express();
app.use(morgan('tiny'));
app.use(express.json());
class HTTPError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
app.post('/ping', async (req, res) => {
const { host } = req.query;
if (!host) {
throw new HTTPError('Error when passing parameters', 400);
}
try {
const pingResult = await ping.promise.probe(host);
if (
['Name or service not known', 'Unknown host'].some((msg) =>
pingResult.output.includes(msg)
)
) {
throw new Error('Unknown host');
}
res.json(pingResult);
} catch (error) {
throw new HTTPError(error.message, 400);
}
});
// 404 handler
app.use((req, res, next) => {
res.status(404).json({ message: 'Content not found!' });
});
// Error handler
app.use((err, req, res, next) => {
if (err instanceof HTTPError) {
return res.status(err.code).json({ message: err.message });
}
// console.error(err.stack);
// next(err)
return res.status(500).json({ message: 'Something broke!' });
});
app.listen(3000, () => {
console.log('App running at http://localhost:3000');
});
/codes/expressjs/system-call/ping-package/requests.http
@server=http://localhost:3000
### Post Ping (with params)
POST {{server}}/ping?host=8.8.8.8
### Post Ping (bad params)
POST {{server}}/ping?host=a.a.a.a
### Post Ping (without params)
POST {{server}}/ping
/codes/expressjs/system-call/ping-package/requests.http
@server=http://localhost:3000
### Post Ping (with params)
POST {{server}}/ping?host=8.8.8.8
### Post Ping (bad params)
POST {{server}}/ping?host=a.a.a.a
### Post Ping (without params)
POST {{server}}/ping