On Linux, the kernel exposes the negotiated link speed of a network interface at /sys/class/net/<iface>/speed (in MBit/s). This post shows a minimal TypeScript class that reads that file and reports whether the interface is connected at gigabit speed or slower.
Ethernet.ts
import { readFile } from "node:fs/promises";
export type CheckStatus = "ok" | "warning" | "error";
export interface CheckResult {
status: CheckStatus;
msg: string;
speedMbps?: number;
}
/**
* Check whether a given ethernet interface is connected and at which link speed,
* by reading /sys/class/net/<iface>/speed.
*/
export class EthernetChecker {
private readonly iface: string;
constructor(iface: string = "eth0") {
this.iface = iface;
}
async check(): Promise<CheckResult> {
let data: string;
try {
data = await readFile(`/sys/class/net/${this.iface}/speed`, "utf8");
} catch (error: any) {
if (error?.code === "ENOENT") {
return { status: "error", msg: `No such interface: ${this.iface}` };
}
// EINVAL is returned by the kernel when the interface has no link
if (error?.code === "EINVAL") {
return { status: "error", msg: `${this.iface} has no link (cable unplugged?)` };
}
return { status: "error", msg: `Could not read link speed: ${error?.message ?? error}` };
}
const speedMbps = Number.parseInt(data.trim(), 10);
if (Number.isNaN(speedMbps)) {
return { status: "error", msg: `Could not parse link speed: ${data.trim()}` };
}
return {
status: speedMbps >= 1000 ? "ok" : "warning",
msg: `${this.iface} connected @${speedMbps} MBit/s`,
speedMbps,
};
}
}Usage example
The check is ok at 1000 MBit/s or faster and warning below that — useful to detect a cable or switch problem that silently downgraded a link to 100 MBit/s:
example.ts
import { EthernetChecker } from "./Ethernet.ts";
console.log(await new EthernetChecker("eth0").check());
// { status: 'warning', msg: 'eth0 connected @100 MBit/s', speedMbps: 100 }
console.log(await new EthernetChecker("nosuch0").check());
// { status: 'error', msg: 'No such interface: nosuch0' }
Note that reading the speed sysfs file fails with EINVAL when the interface is up but has no carrier, so an unplugged cable is reported as an error rather than a parsed value.
Check out similar posts by category:
TypeScript Linux Networking
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow