How to use sprintf instead of hardcoded values
I am developing a firewall for Linux as my project. I am able to captu开发者_高级运维re packets and to block them. I am using IPTABLES.
How can I use variables with sprintf instead of hardcoded values?
sprintf(comm, "iptables -A INPUT -s $str -j DROP")
// inplace of:
sprintf(comm, "iptables -A INPUT -s 192.168.0.43 -j DROP")
sprintf(comm, "iptables -A INPUT -s %s -j DROP", "192.168.0.43");
// also:
char ipaddress[] = "192.168.0.43";
sprintf(comm, "iptables -A INPUT -s %s -j DROP", ipaddress);
Read more in man sprintf.
It works just like regular printf()
. Same format strings are accepted. However, be careful to avoid overflowing the string buffer. In that sense, snprintf()
will be MUCH more acceptable than sprintf()
.
精彩评论