新版本采用libipset库操作ipset集合,采用libpcap、libcap抓包获取源IP
This commit is contained in:
61
common.c
61
common.c
@@ -17,7 +17,7 @@ int _strlen(char *str)
|
||||
}
|
||||
|
||||
// 自定义 printf 函数
|
||||
void my_printf(const char *format, ...)
|
||||
void _printf(const char *format, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
@@ -51,6 +51,7 @@ void my_printf(const char *format, ...)
|
||||
perror("Unable to open log file");
|
||||
}
|
||||
|
||||
|
||||
va_end(args); // 结束对变参列表的处理
|
||||
}
|
||||
|
||||
@@ -117,7 +118,7 @@ int isregion(char *str, char (*region_list)[WHITELIST_IP_NUM])
|
||||
return 0; // 没有匹配,返回0
|
||||
}
|
||||
|
||||
int8_t copy_new_mem(char *src, int src_len, char **dest)
|
||||
int8_t _copy_new_mem(char *src, int src_len, char **dest)
|
||||
{
|
||||
*dest = (char *)malloc(src_len + 1);
|
||||
if (*dest == NULL)
|
||||
@@ -152,7 +153,7 @@ int is_valid_ip(const char *ip)
|
||||
return result != 0;
|
||||
}
|
||||
|
||||
int nice_(int increment)
|
||||
int _nice(int increment)
|
||||
{
|
||||
int oldprio = getpriority(PRIO_PROCESS, getpid());
|
||||
printf("%d\n", oldprio);
|
||||
@@ -161,11 +162,61 @@ int nice_(int increment)
|
||||
}
|
||||
|
||||
// 判断命令是否存在
|
||||
int command_exists(const char *command)
|
||||
int _command_exists(const char *command)
|
||||
{
|
||||
char buffer[BUFFER];
|
||||
snprintf(buffer, sizeof(buffer), "%s > /dev/null 2>&1", command);
|
||||
int status = system(buffer);
|
||||
|
||||
return (status == 0);
|
||||
}
|
||||
}
|
||||
|
||||
// 定义一个函数,执行命令并返回输出
|
||||
char *_execute_command(const char *command) {
|
||||
FILE *fp;
|
||||
char buffer[1024];
|
||||
char *output = NULL;
|
||||
size_t output_size = 0;
|
||||
size_t total_read = 0;
|
||||
|
||||
// 打开管道,执行命令
|
||||
fp = popen(command, "r");
|
||||
if (fp == NULL) {
|
||||
perror("popen");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 读取命令的输出
|
||||
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
|
||||
size_t len = strlen(buffer);
|
||||
if (total_read + len + 1 > output_size) {
|
||||
output_size = output_size == 0 ? 128 : output_size * 2;
|
||||
char *new_output = realloc(output, output_size);
|
||||
if (new_output == NULL) {
|
||||
perror("realloc");
|
||||
free(output); // 释放已分配的内存
|
||||
pclose(fp); // 关闭管道
|
||||
return NULL;
|
||||
}
|
||||
output = new_output;
|
||||
}
|
||||
// 复制内容并增加总计读取的长度
|
||||
strcpy(output + total_read, buffer);
|
||||
total_read += len;
|
||||
}
|
||||
|
||||
// 确保输出以 null 结尾
|
||||
if (output_size > 0) {
|
||||
output[total_read] = '\0';
|
||||
}
|
||||
|
||||
// 关闭管道
|
||||
if (pclose(fp) == -1) {
|
||||
perror("pclose");
|
||||
free(output); // pclose 失败时释放内存
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user