Mac OS 上使用 C++ 编写随机数据包发送程序
Mac OS 上使用 C++ 编写随机数据包发送程序
本教程将指导您使用 C++ 在 Mac OS 上编写一个程序,该程序可以模拟 100 台计算机向指定网站发送随机数据包。
代码
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define NUM_COMPUTERS 100
#define NUM_PACKETS 10
#define SERVER_IP '127.0.0.1'
#define SERVER_PORT 8080
int main() {
srand(time(nullptr));
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
std::cerr << 'Error creating socket.' << std::endl;
return 1;
}
sockaddr_in server_addr{};
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
if (inet_aton(SERVER_IP, &server_addr.sin_addr) == 0) {
std::cerr << 'Invalid IP address.' << std::endl;
return 1;
}
for (int i = 0; i < NUM_COMPUTERS; ++i) {
for (int j = 0; j < NUM_PACKETS; ++j) {
uint8_t packet[1024];
int packet_len = rand() % 1024;
for (int k = 0; k < packet_len; ++k) {
packet[k] = rand() % 256;
}
sendto(sockfd, packet, packet_len, 0, (sockaddr*)&server_addr, sizeof(server_addr));
usleep(1000); // Wait 1 ms before sending next packet
}
}
close(sockfd);
return 0;
}
注意事项
- 该程序需要在命令行中编译并运行。
- 在 Mac OS 中,使用 g++ 编译器编译该程序的命令为:
g++ -o program program.cpp。 - 在运行该程序前,需要启动一个接收数据包的服务器,并将服务器 IP 和端口号设置为程序中的常量
SERVER_IP和SERVER_PORT。
原文地址: https://www.cveoy.top/t/topic/nw3T 著作权归作者所有。请勿转载和采集!