Linux中的ping命令用于测试网络连接。当使用ping命令时,会发送ICMP消息到目标主机并等待其返回响应。根据不同情况,ping命令可能会返回以下状态码:
- 0:成功收到了来自目标主机的响应。这意味着网络连接正常且目标主机处于活动状态
- 1:目标主机不可达,可能是由于网络故障、目标主机关闭或防火墙设置等原因
- 其他非零值:其他错误
应用程序可以利用这个特性判断指定IP是否能ping通,代码如下:
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
/*
*****************************************************************************************
* 函 数 名: run_ping
* 功能说明: 运行ping命令,并判断是否成功
* 形 参:无
* 返 回 值: 0:ping成功
* -1:失败
*****************************************************************************************
*/
int run_ping(char *_pIpAddr) {
int cnt = 0;
int result = 0;
pid_t pid;
if ((pid = vfork()) < 0) {
printf("%s: vfork error: %s
", __FUNCTION__, strerror(errno));
return -1;
} else if (pid == 0) { //子进程
if (execlp("ping", "ping","-c","1", _pIpAddr, (char*)0) < 0) {
printf("%s: execlp error: %s
", __FUNCTION__, strerror(errno));
return -1;
}
}
waitpid(pid, &result, 0);
if (WIFEXITED(result)) {
if (WEXITSTATUS(result) != 0) {
printf("%s: execute command: %s failed(%d)
", __FUNCTION__, "ping", WEXITSTATUS(result));
result = -1;
} else {
result = 0;
}
} else {
result = 0;
}
if (result) {
printf("ping %s error!
", _pIpAddr);
return -1;
} else {
printf("ping %s ok!
", _pIpAddr);
return 0;
}
}
#define TEST_IP "183.2.172.185"
#define ERROR_IP "192.168.100.100"
int main(void){
run_ping(TEST_IP);
run_ping(ERROR_IP);
}
执行结果:

当然,还有其他方法,如:根据ping命令原理,用socket实现 ICMP 协议。