如果应用程序需要频繁的修改防火墙规则,那么可以用如下的办法来提高性能。
比如需要执行iptables -s 10.10.1.1 -j DROP等诸如此类。
对比一下前后效率(以循环5次来比较):
1 直接执行system("iptables ...."); 用时46914us
2 不用system,而用iptables中的函数do_command; 用时622us
性能有差不多70倍的提升
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <iptables.h>
#include<sys/time.h>
#include<sys/ioctl.h>
#include <unistd.h>
unsigned long span;
struct timeval time1,time2;
int
main(int argc, char *argv[])
{
int ret;
char *table = "filter";
iptc_handle_t handle = NULL;
program_name = "iptables";
program_version = IPTABLES_VERSION;
#ifdef NO_SHARED_LIBS
init_extensions();
#endif
//FILE *file;
//int oldfd = dup( STDOUT_FILENO );
int i;
//freopen( "/dev/null", "w", stdout );
gettimeofday(&time1,NULL);
argv[0] = "myipt";
argv[1] = "-A";
argv[2] = "INPUT";
argv[3] = "-s";
argv[4] = "10.10.1.1";
argv[5] = "-j";
argv[6] = "DROP";
argc = 7;
for(i=0;i<5;i++)
{
ret = do_command(argc,argv, &table, &handle);
if (ret)
ret = iptc_commit(&handle);
if (!ret)
fprintf(stderr, "iptables: %s
",
iptc_strerror(errno));
}
gettimeofday(&time2,NULL);
span=(time2.tv_sec-time1.tv_sec)*1000000+(time2.tv_usec-time1.tv_usec);
//file = fdopen( oldfd, "w" );
//stdout = file;
printf("times cost: %lu us
",span);
gettimeofday(&time1,NULL);
char exec_str[128];
for(i=0;i<5;i++)
{
strcpy(exec_str,"iptables -A INPUT -s 10.10.1.1 -j DROP");
system(exec_str);
}
gettimeofday(&time2,NULL);
span=(time2.tv_sec-time1.tv_sec)*1000000+(time2.tv_usec-time1.tv_usec);
printf("times cost: %lu us
",span);
exit(!ret);
}