开发者

i just want to use the iptables command in my c program

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..


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜