如何用C语言编写一个网络连通性测试简单脚本输出测试后文档
时间: 2024-10-10 15:09:47 浏览: 25
纯C语言车牌识别代码
在C语言中编写一个网络连通性测试脚本,可以使用socket编程的基本原理检测到目标主机是否可达。以下是一个简单的示例,测试完后你可以生成一个文档记录结果:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int is_connected(char* host, int port) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
fprintf(stderr, "Error creating socket: %s\n", strerror(errno));
return 1;
}
struct sockaddr_in server_address;
bzero(&server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);
inet_aton(host, &server_address.sin_addr);
int result = connect(sock, (struct sockaddr*)&server_address, sizeof(server_address));
close(sock);
if (result == 0) {
printf("%s:%d is connected.\n", host, port);
return 0; // 连接成功
} else {
fprintf(stderr, "Failed to connect to %s:%d: %s\n", host, port, strerror(errno));
return 1; // 连接失败
}
}
// 测试函数
void test_network_connection(const char* hosts[], int num_hosts) {
for (int i = 0; i < num_hosts; ++i) {
int status = is_connected(hosts[i], 80); // 假设HTTP默认端口
if (status == 1) {
fprintf(stderr, "Could not connect to %s.\n", hosts[i]);
}
}
}
int main() {
const char* hosts[] = {"www.google.com", "www.baidu.com", "localhost"};
int num_hosts = sizeof(hosts) / sizeof(hosts[0]);
test_network_connection(hosts, num_hosts);
return 0;
}
阅读全文