这是一个使用liboping 每秒ping www.xively.com 并显示延迟的小代码。您可以像这样在 ubuntu 机器上安装 liboping 静态/动态库文件和头文件:sudo apt-get install liboping0 liboping-dev oping
然后使用上述库 ( gcc -o test test.c -loping
) 编译以下程序。并以超级用户 (sudo) 身份运行可执行文件。
测试.c:
/*
* 1. install liboping, e.g. `sudo apt-get install liboping0 liboping-dev oping`
* 2. Compile with -loping, e.g. `gcc -o test test.c -loping`
* 3. Execute using sudo as super user, e.g. `sudo ./test`
*/
#include <stdlib.h>
#include <stdio.h>
#include <oping.h>
int main(int argc, char **argv) {
pingobj_t *ping;
pingobj_iter_t *iter;
if ((ping = ping_construct()) == NULL) {
fprintf(stderr, "ping_construct failed\n");
return -1;
}
printf("ping_construct() success\n");
if (ping_host_add(ping, "www.xively.com") < 0) {
const char * errmsg = ping_get_error(ping);
fprintf(stderr, "ping_host_add(www.xively.com) failed. %s\n", errmsg);
return -1;
}
printf("ping_host_add() success\n");
while (1) {
if (ping_send(ping) < 0) {
fprintf(stderr, "ping_send failed\n");
return -1;
}
printf("ping_send() success\n");
for (iter = ping_iterator_get(ping); iter != NULL; iter =
ping_iterator_next(iter)) {
char hostname[100];
double latency;
unsigned int len;
printf("ping_iterator_get() success\n");
len = 100;
ping_iterator_get_info(iter, PING_INFO_HOSTNAME, hostname, &len);
len = sizeof(double);
ping_iterator_get_info(iter, PING_INFO_LATENCY, &latency, &len);
printf("hostname = %s, latency = %f\n", hostname, latency);
}
sleep(1);
}
printf("exiting...\n");
ping_destroy( ping );
return 0;
}
输出:
anurag@anurag-PC:~$ sudo ./test
ping_construct() success
ping_host_add() success
ping_send() success
ping_iterator_get() success
hostname = www.xively.com, latency = 233.666000
ping_send() success
ping_iterator_get() success
hostname = www.xively.com, latency = 234.360000
ping_send() success
ping_iterator_get() success
hostname = www.xively.com, latency = 234.076000
ping_send() success
ping_iterator_get() success
hostname = www.xively.com, latency = 231.761000
ping_send() success
ping_iterator_get() success
hostname = www.xively.com, latency = 235.085000
^C
如果您想从 linux 设备检查互联网连接,只要您的 ISP 或目标不阻止 ICMP 数据包,liboping 就很好。如果这些被阻止,您可以使用一些 HTTP 库尝试从 www.google.com 或任何其他网站获取 index.html 页面并检查是否成功