下面是一个简单的 C 语言程序示例,使用 ping
命令行工具来发送指定数量和长度的 ICMP 回显请求(ping 包)。由于 C 语言标准库不直接支持 ICMP 操作,我们将利用 system()
函数来调用系统的 ping
命令。
#include <stdio.h>
#include <stdlib.h>
void send_ping(const char *ip, int count, int size) {
char command[256];
snprintf(command, sizeof(command), "ping -c %d -s %d %s", count, size, ip);
system(command);
}
int main() {
const char *ip_address = "192.168.15.3";
// Send 100 pings of length 200
printf("Sending 100 pings of length 200 to %s\n", ip_address);
send_ping(ip_address, 100, 200);
// Send 50 pings of length 400
printf("Sending 50 pings of length 400 to %s\n", ip_address);
send_ping(ip_address, 50, 400);
return 0;
}
解释:
send_ping
函数:构造ping
命令并使用system()
执行。-c
指定发送的包数,-s
指定数据包的大小。main
函数:调用send_ping
函数两次,分别发送不同数量和长度的 ping 包。
注意:
- 确保
ping
命令在你的系统上可用,并且命令选项(-c
和-s
)适用于你的操作系统。Linux 和 macOS 的ping
命令支持这些选项,但在 Windows 上可能需要调整命令。 - 运行此程序可能需要管理员权限,具体取决于系统的配置和权限设置。