1

I am developing a firewall for Linux as my project. I am able to capture 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") 

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

thanks but it gives an error of incompatible types nw wht to do??? actually i want to use iptables commands in my c program its working for static ipaddress but i want to do that for dynamically
What exactly does the error say? Are you following the snprintf() documentation?
@astha: It sounds like you need to learn about general string manipulation in C, which is a stumbling block for many new programmers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.