-1

I want to execute a variable inside system(""). For example like

system("iptables -i input -s VARIABLE -j drop")

VARIABLE here is an IP address but it'll change everytime.

how can i do that in C++ ? if it's not , then what's the solution ?

2
  • Didn't system("iptables -i input -s $VARIABLE -j drop") work? What's your operating system? Commented May 22, 2016 at 10:05
  • try std::execl. usage example is : execl( "/bin/ls", "ls", "-l", (char*)0 ); Commented May 22, 2016 at 10:08

4 Answers 4

2

Use a std::string for the command:

std::string cmd = "iptables -i input -s ";
std::string ipaddr = "192.168.11.22";
cmd += ipaddr;
cmd += "  -j drop";
system(cmd.c_str());

Or a bit simpler using std::ostringstream:

std::string ipaddr = "192.168.11.22";
std::ostringstream oss;
oss << "iptables -i input -s " << ipaddr << " -j drop";
system(oss.str().c_str());
Sign up to request clarification or add additional context in comments.

2 Comments

I not sure if it is that much simpler - 6 of one and half a dozen of the other
thank you so much, it works... and i try this with the array string, and it works too. thanks a lot..
1

Try this

string cmd = "iptables -i input -s ";
cmd += VARIABLE;
cmd += " -j drop";
system(cmd.c_str());

Here the command is constructed to include the variable.

Comments

0

You generate the string at runtime. For example:

std::string varip = somefunctiongivingastring();
std::string cmdstr= "iptables -i input -s " + varip + " -j drop";

Then you pass it to system by converting it to a raw const char* with

system (cmdstring.c_str());

You could do the same in C like

char cmdbuf[256];
char* varip = somfunctiongivingacstring();
snprintf (cmdbuf, sizeof(cmdbuf), "iptables -i input -s %s -j drop", varip);

However, beware of code injection; imagine what could happen if somefunctiongivingacstring() would return the "127.0.0.1; rm -rf $HOME; echo "string

Comments

0

You can generate the string at run-time using the following code (the ip address can be replaced with a string variable):

std::string ipAddress = "127.0.0.1";
std::stringstream ss;
ss << "iptables -i input -s " + ipAddress + " -j drop";
system(ss.str());

In order to compile this code correctly you need to include the following header file:

#include <sstream>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.