tags:

views:

184

answers:

2

i m designing a simple c code to call the iptables command according to the need. i just want to drop the packets from a particular ipaddress using my c code. thats why i have to use the iptables command according to input given. is it possible to call the command using c code? if it is then how??? thanks in advance..

+2  A: 

Assuming that your program is running as root, just use fork() and exec(), and pass the iptables command to exec(). Something like

if (0 == fork()) {
    execl("/sbin/iptables", ...); // supply the proper arguments to iptables.
}

Edit: I see from other people that system() is a better way than fork/exec.

It sounds like Neha is not sure how to use sprintf to format the command so that it contains an IP address which is stored in some other variable. I think it should look like this:

char *host_to_block = ....
char comm[1000];
snprintf(comm, sizeof(comm), "iptables -A INPUT -s %s -j DROP", host_to_block);
system(comm);

Note that this will be a security vulnerability unless you have code to verify that host_to_block contains an IP address and not some other shell command. You may want to use the following question for reference if the source of the string is not already known to be valid:

how to validate an ip address

Paul Tillotson
Rather than using system(), then use fork followed by an execl of /sbin/iptables, and put the IP address into its own element in the args array. That way you don't run a shell process, and there's no way a shell injection could happen (incidentally it's slightly more efficient too, but that is irrelevant)
MarkR
+1  A: 

It is possible to do this without using the system() or exec*() family of commands, however I'm sure that you are also interested in actually completing your project :)

If, however you only need very rudimentary functionality from iptables within your program, or need precision error handling, you can obtain the source to the iptables package.

Advanced warning: studying the iptables ioctl hooks and the corresponding netfilter modules is known to be a mind liquefying task.

Tim Post
+1 for mentioning underlying OS interface, i.e. the proper way to do it.
Tadeusz A. Kadłubowski
Invoking /sbin/iptables is the RIGHT way to do it however, according to the Netfilter web site. The kernel interfaces (or indeed the C library) are no intended to be a stable API.
MarkR