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.
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.
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
.
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);
}