简体   繁体   English

通过C exec()执行IPtables

[英]executing IPtables via C exec()

I'm trying to make a program here that blocks an IP address given an IP address as an input string, and even though the program executes in the background, the parameters seem to be passed incorrectly. 我正在尝试制作一个程序来阻止给定IP地址作为输入字符串的IP地址,尽管该程序在后台执行,但参数似乎传递不正确。

I'm trying to execute the following using my function: 我正在尝试使用我的函数执行以下操作:

iptables -A INPUT -p tcp --dport 21 -s xxx.xxx.xxx.xxx -j DROP

I tried the command by typing it in manually on the command-line and it worked there, but my program does not seem to process the command the same way. 我通过在命令行上手动键入命令来尝试该命令,并且该命令在此处起作用,但是我的程序似乎无法以相同方式处理该命令。 How do I fix my function so that the program issues the parameters as shown in the sample command above? 如何修复我的函数,以便程序发出上面示例命令中所示的参数? I also want to avoid using the system() call. 我也想避免使用system()调用。

Here's my function: 这是我的功能:

function blockip(char* ip){
    char parameter[500];
    sprintf(parameter,"-s %s",ip);
    char*args[20]={"-A INPUT","-p tcp --dport 21",parameter,"-j DROP",NULL};
    int stat,pid=fork();
    if (pid==0){
       execvp("iptables",args);
    }
    waitpid(pid,&stat,0);
}

You need to separate out each value individually. 您需要单独分隔每个值。 Arguments separated by spaces on the command line should be separate array elements. 命令行上用空格分隔的参数应为单独的数组元素。 The first argument in the argument list is always the name of the program. 参数列表中的第一个参数始终是程序的名称。

Also, make sure to do proper error checking of fork and execvp . 另外,请确保对forkexecvp进行正确的错误检查。

void blockip(char* ip){
    char *args[]={"iptables", "-A", "INPUT", "-p", "tcp", 
                 "--dport", "21", "-s", ip, "-j", "DROP", NULL };
    int stat,pid=fork();
    if (pid==-1) {
        perror("fork failed");
        return;
    if (pid==0){
       execvp("iptables",args);
       perror("exec failed");
       exit(1);
    }
    waitpid(pid,&stat,0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM