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