create a http server with a trace route in typescript

Here's an example of how to create an HTTP server with a trace route using TypeScript and the Express framework:

index.ts
import express from 'express';
import { createConnection } from 'net';
import { promisify } from 'util';

const app = express();

app.get('/traceroute', async (req, res) => {
  const host = req.query.host as string;

  const traceRoute = async (host: string) => {
    const traceroute = promisify(createConnection);
    const hops = [];

    for (let ttl = 1; ttl <= 30; ttl++) {
      try {
        const socket = await traceroute({
          host,
          ttl,
          timeout: 2000,
        });

        hops.push({
          ttl,
          address: socket.remoteAddress,
          duration: socket.duration,
        });

        socket.destroy();
      } catch (error) {
        console.error(error);
        hops.push({
          ttl,
          address: '*',
          duration: null,
        });
      }
    }

    return hops;
  };

  const hops = await traceRoute(host);

  res.json({ hops });
});

const port = 3000;

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
1021 chars
52 lines

This code listens for incoming requests to /traceroute. The host parameter is extracted from the query string and passed to the traceRoute function.

The traceRoute function sends packets to the target host with progressively increasing Time-to-Live (TTL) values. Each time a packet is sent, the function records the IP address and response time of the router that responded to the packet.

The hops array containing this information is returned as a JSON response to the client.

Note that this code uses the net module's createConnection method to send packets directly using TCP/IP. This is not the same as using the standard ICMP-based traceroute command that is available on most operating systems, but it can provide similar information in some cases.

gistlibby LogSnag