Skip to content

Instantly share code, notes, and snippets.

@kesselb
Created October 21, 2020 19:31
Show Gist options
  • Save kesselb/1d40c6f3c3491c8ecd59dcbb4ae5ea8d to your computer and use it in GitHub Desktop.
Save kesselb/1d40c6f3c3491c8ecd59dcbb4ae5ea8d to your computer and use it in GitHub Desktop.
<?php
const PATTERN_LINK = '/^(?<index>\d+):\s+(?<device>[\w\-]+).+state (?<state>UNKNOWN|UP|DOWN).+link\/(loopback|ether) (?<address>[a-z0-9\:]+)/';
const PATTERN_IPv4 = '/^(?<index>\d+):\s*(?<device>[\w\-]+)\s+inet (?<ipv4>[0-9\.\/]+)/';
const PATTERN_IPv6 = '/^(?<index>\d+):\s*(?<device>[\w\-]+)\s+inet6 (?<ipv6>[a-z0-9\:\/]+)/';
$interfaces = [];
$result = shell_exec('ip -o link show');
$rows = explode(PHP_EOL, $result);
foreach ($rows as $row) {
$matches = [];
if (preg_match(PATTERN_LINK, $row, $matches) === 1) {
$device = $matches['device'];
$interface = [
'device' => $device,
'state' => $matches['state'],
'address' => $matches['address'],
'speed' => null,
'duplex' => null,
'ipv4' => [],
'ipv6' => [],
];
$fileSpeed = '/sys/class/net/' . $device . '/speed';
$interface['speed'] = trim(@file_get_contents($fileSpeed));
$fileDuplex = '/sys/class/net/' . $device . '/duplex';
$interface['duplex'] = trim(@file_get_contents($fileDuplex));
$interfaces[$device] = $interface;
}
}
$result = shell_exec('ip -o addr show');
$rows = explode(PHP_EOL, $result);
foreach ($rows as $row) {
$matches = [];
if (preg_match(PATTERN_IPv4, $row, $matches) === 1) {
// IPv4
$device = $matches['device'];
$ipv4 = $matches['ipv4'];
if (isset($interfaces[$device])) {
$interfaces[$device]['ipv4'][] = $ipv4;
}
}
if (preg_match(PATTERN_IPv6, $row, $matches) === 1) {
// IPv6
$device = $matches['device'];
$ipv6 = $matches['ipv6'];
if (isset($interfaces[$device])) {
$interfaces[$device]['ipv6'][] = $ipv6;
}
}
}
var_dump($interfaces);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment