帮我写一个利用http ping进行链路检测的C语言代码
时间: 2024-05-04 20:20:56 浏览: 73
以下是一个简单的利用http ping进行链路检测的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
int main(int argc, char *argv[]) {
if (argc 2) {
printf("Usage: %s <hostname>\n", argv[0 exit(1);
}
char *hostname = argv[1];
struct host *host = gethostbyname(hostname);
if (!host) {
printf("Error: not resolve hostname.\n");
exit(1);
}
struct sockaddr_in addr;
memcpy(&addr.sin_addr.s_addr, host->h_addr, 4);
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
printf("Error: could not create socket.\n");
exit(1);
}
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
printf("Error: could not connect to host.\n");
exit(1);
}
char *request = "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n";
char buffer[1024] = {0};
sprintf(buffer, request, hostname);
clock_t start = clock();
if (send(sock, buffer, strlen(buffer), 0) < 0) {
printf("Error: could not send request.\n");
exit(1);
}
if (recv(sock, buffer, sizeof(buffer), 0) < 0) {
printf("Error: could not receive response.\n");
exit(1);
}
clock_t end = clock();
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
printf("Response received in %lf seconds.\n", time_spent);
close(sock);
return 0;
}
```
该代码通过获取用户输入的主机名,使用 `gethostbyname()` 函数解析主机名,获取主机的 IP 地址。然后创建一个 TCP 套接字并连接到主机的 HTTP 端口(端口号为 80)。接着发送 HTTP GET 请求,并计算请求到响应的时间。最后关闭套接字。
需要注意的是,该代码只能测试主机是否能够响应 HTTP 请求,不能测试完整的网络链路的可用性。
阅读全文