20250423
This commit is contained in:
25
cache.c
25
cache.c
@@ -1,6 +1,5 @@
|
||||
#include "cache.h"
|
||||
|
||||
|
||||
struct ip_cache_node *ip_cache_head = NULL; // 缓存链表的头节点
|
||||
int cache_size = 0; // 当前缓存中的 IP 数量
|
||||
|
||||
@@ -27,7 +26,6 @@ void add_ip_to_cache(const char *ip)
|
||||
free(current);
|
||||
cache_size--;
|
||||
}
|
||||
|
||||
// 创建新的缓存节点并添加到链表头部
|
||||
struct ip_cache_node *new_node = (struct ip_cache_node *)malloc(sizeof(struct ip_cache_node));
|
||||
if (new_node == NULL) {
|
||||
@@ -48,7 +46,8 @@ int is_ip_in_cache(const char *ip)
|
||||
struct ip_cache_node *current = ip_cache_head;
|
||||
struct ip_cache_node *prev = NULL;
|
||||
|
||||
if (ip_cache_head == NULL) return 0; // 如果 ip_cache_head == NULL,current->next 可能导致段错误 (Segmentation Fault)。
|
||||
if (ip_cache_head == NULL)
|
||||
return 0; // 如果 ip_cache_head == NULL,current->next 可能导致段错误 (Segmentation Fault)。
|
||||
|
||||
while (current != NULL) {
|
||||
// 如果 IP 匹配并且未过期
|
||||
@@ -89,8 +88,6 @@ void free_ip_cache()
|
||||
cache_size = 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
char cn_ip[MAXIPSET_][MAXIPLEN] = { 0 };
|
||||
|
||||
// 添加一个 IP 到集合(如果已存在则不添加)
|
||||
@@ -133,20 +130,38 @@ int is_ip_in_set(char cn_ip[MAXIPSET_][MAXIPLEN], const char *ip)
|
||||
int cn_ip_len(char cn_ip[MAXIPSET_][MAXIPLEN])
|
||||
{
|
||||
int count = 0; // 用于计数非空IP
|
||||
|
||||
for (int i = 0; i < MAXIPSET_; i++) {
|
||||
if (cn_ip[i][0] != '\0') {
|
||||
count++; // 非空IP计数
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
int truncate_file(const char *path)
|
||||
{
|
||||
int fd;
|
||||
|
||||
// 以只写模式打开文件并截断到0字节
|
||||
fd = open(path, O_WRONLY | O_TRUNC);
|
||||
if (fd == -1) {
|
||||
perror("truncate_file: Failed to open file");
|
||||
return -1;
|
||||
}
|
||||
// 关闭文件描述符(此时文件已被截断)
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 安全的清理IP地址集合,将所有位置置为空字符串
|
||||
void clear_ip_set(char cn_ip[MAXIPSET_][MAXIPLEN])
|
||||
{
|
||||
if (cn_ip == NULL) {
|
||||
return; // 如果指针无效,则直接返回
|
||||
}
|
||||
|
||||
for (int i = 0; i < MAXIPSET_; i++) {
|
||||
memset(cn_ip[i], '\0', MAXIPLEN);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user