jelasin 的學生作業(yè):
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFFER_SIZE 1024
#define LOG_FILE "log.txt"
#define RECV_IP "127.0.0.1"
#define RECV_PORT 9090
void create_log_file() {
FILE *fp = fopen(LOG_FILE, "w");
if (!fp) {
perror("fopen failed");
exit(EXIT_FAILURE);
}
const char *test_data[] = {
"==== UDP File Transfer Test ====\n",
"Line 1: Hello UDP World!\n",
"Line 2: This is a test message\n",
"Line 3: 1234567890\n",
"==== End of Transmission ====\n"
};
for (size_t i = 0; i < sizeof(test_data)/sizeof(test_data[0]); i++) {
fputs(test_data[i], fp);
}
fclose(fp);
printf("[Sender] Created %s with test data\n", LOG_FILE);
}
char *read_log_file(size_t *file_size) {
FILE *fp = fopen(LOG_FILE, "r");
if (!fp) {
perror("fopen failed");
return NULL;
}
fseek(fp, 0, SEEK_END);
*file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buffer = malloc(*file_size + 1);
if (!buffer) {
perror("malloc failed");
fclose(fp);
return NULL;
}
size_t read_size = fread(buffer, 1, *file_size, fp);
if (read_size != *file_size) {
perror("fread failed");
free(buffer);
fclose(fp);
return NULL;
}
buffer[*file_size] = '\0';
fclose(fp);
return buffer;
}
int main() {
// 1. 創(chuàng)建日志文件
create_log_file();
// 2. 讀取文件內容
size_t file_size;
char *file_content = read_log_file(&file_size);
if (!file_content) {
fprintf(stderr, "[Sender] Failed to read log file\n");
return EXIT_FAILURE;
}
printf("[Sender] File content (%zu bytes):\n%s\n", file_size, file_content);
// 3. 創(chuàng)建UDP socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("[Sender] socket creation failed");
free(file_content);
return EXIT_FAILURE;
}
// 設置接收方地址
struct sockaddr_in recv_addr = {
.sin_family = AF_INET,
.sin_port = htons(RECV_PORT)
};
if (inet_pton(AF_INET, RECV_IP, &recv_addr.sin_addr)