PHP net_get_interfaces 函数
最后修改于 2025 年 4 月 4 日
PHP net_get_interfaces 函数用于检索网络接口信息。它提供系统中所有网络接口的详细信息。
基本定义
net_get_interfaces 返回一个关联数组,其中包含网络接口。每个接口都包含 IP 地址和 MAC 地址等详细信息。
语法: net_get_interfaces(): array|false。成功时返回数组,失败时返回 false。PHP 7.3 及更高版本可用。
基本接口列表
此示例演示如何获取和显示所有网络接口。
basic_interfaces.php
<?php
declare(strict_types=1);
$interfaces = net_get_interfaces();
if ($interfaces === false) {
echo "Failed to get network interfaces";
exit(1);
}
print_r($interfaces);
此代码检索所有网络接口并打印其详细信息。输出包括接口名称、IP 地址和 MAC 地址。
检查特定接口
此示例演示如何检查特定网络接口是否存在。
check_interface.php
<?php
declare(strict_types=1);
$interfaces = net_get_interfaces();
$target = "eth0";
if (isset($interfaces[$target])) {
echo "Interface $target exists";
print_r($interfaces[$target]);
} else {
echo "Interface $target not found";
}
此代码检查 'eth0' 接口是否存在。如果找到,则显示接口详细信息,包括 IP 配置和状态。
列出 IP 地址
此示例提取并列出所有接口的所有 IPv4 地址。
list_ips.php
<?php
declare(strict_types=1);
$interfaces = net_get_interfaces();
foreach ($interfaces as $name => $details) {
if (isset($details['unicast'])) {
foreach ($details['unicast'] as $addr) {
if ($addr['family'] == 2) { // AF_INET
echo "$name: {$addr['address']}\n";
}
}
}
}
此代码循环遍历所有接口及其单播地址。它过滤 IPv4 地址(族 2)并与接口名称一起打印。
检查接口状态
此示例显示如何检查网络接口是否正在运行。
interface_status.php
<?php
declare(strict_types=1);
$interfaces = net_get_interfaces();
$target = "wlan0";
if (isset($interfaces[$target])) {
$status = $interfaces[$target]['up'] ? "up" : "down";
echo "Interface $target is $status";
} else {
echo "Interface $target not found";
}
此代码检查 'wlan0' 接口的 'up'(运行)状态。'up' 字段指示接口当前是否处于活动状态并可正常工作。
获取 MAC 地址
此示例演示如何检索所有接口的 MAC 地址。
mac_addresses.php
<?php
declare(strict_types=1);
$interfaces = net_get_interfaces();
foreach ($interfaces as $name => $details) {
if (isset($details['mac'])) {
echo "$name: {$details['mac']}\n";
} else {
echo "$name: No MAC address\n";
}
}
此代码列出所有接口及其 MAC 地址。某些接口(如回环接口)可能没有 MAC 地址。输出显示每个接口的硬件地址。
最佳实践
- 错误处理:始终检查 false 返回值
- 权限:确保脚本具有适当的权限
- 缓存:缓存结果以供重复使用
- 安全:谨慎处理敏感网络信息
来源
本教程通过实际示例涵盖了 PHP net_get_interfaces 函数在网络接口信息检索方面的应用。
作者
列出 所有 PHP 网络函数。