You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Linux的ping命令检测网址可达性并仅返回True/False?

用ping命令实现仅返回True/False的可达性测试

Windows 系统

CMD/批处理环境

使用以下命令,通过判断ping的退出码输出True或False:

ping -n 1 -w 1000 address.com >nul && echo True || echo False

参数说明:

  • -n 1:仅发送1个ICMP数据包,缩短测试时间
  • -w 1000:设置超时时间为1000毫秒(1秒)
  • >nul:屏蔽ping命令的所有输出内容
  • &&/||:根据ping命令的执行结果跳转,成功则输出True,失败输出False

PowerShell环境

如果想在PowerShell中用原生ping命令实现类似效果,可执行:

ping -n 1 -w 1000 address.com *>&1 | Out-Null
if ($LASTEXITCODE -eq 0) { Write-Output $true } else { Write-Output $false }

或者更简洁的单行写法:

[bool](ping -n 1 -w 1000 address.com *>&1 | Where-Object { $_ -match "Reply from" })

Linux/macOS 系统

在bash、zsh等终端环境中,使用以下命令:

ping -c 1 -W 1 address.com >/dev/null 2>&1 && echo "True" || echo "False"

参数说明:

  • -c 1:仅发送1个ICMP数据包
  • -W 1:设置超时时间为1秒
  • >/dev/null 2>&1:屏蔽所有标准输出和错误输出
  • &&/||:根据ping的执行结果输出对应布尔值

如果需要在脚本中直接获取布尔状态(用0/1表示):

ping -c 1 -W 1 address.com >/dev/null 2>&1
echo $?

返回0代表可达(对应True),非0值代表不可达(对应False)。

内容的提问来源于stack exchange,提问作者Lena Mori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:36:10