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

IFL
  • 5
  • 1
  • 3

4 Answers4

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());
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • I not sure if it is that much simpler - 6 of one and half a dozen of the other – Ed Heal May 22 '16 at 10:13
  • thank you so much, it works... and i try this with the array string, and it works too. thanks a lot.. – IFL May 23 '16 at 02:59
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.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
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

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
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>
Francesco Argese
  • 626
  • 4
  • 11