I have wrote a c++ code to share internet from wlan0 or eth1 with eth0 and code works properly.
code to share eth1 with eth0:
cmd = "systemctl stop networking";
system(cmd.c_str());
cmd = "iptables -A FORWARD -o eth1 -i eth0 -s 192.168.2.0/24 -m conntrack --ctstate NEW -j ACCEPT";
system(cmd.c_str());
cmd = "ptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT";
system(cmd.c_str());
cmd = "iptables -t nat -F POSTROUTING";
system(cmd.c_str());
cmd = "iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE";
system(cmd.c_str());
cmd = "iptables-save | tee /etc/iptables.sav";
system(cmd.c_str());
cmd = "iptables-restore < /etc/iptables.sav";
system(cmd.c_str());
cmd = "sysctl net.ipv4.ip_forward=1";
system(cmd.c_str());
cmd = "ip route add default via 192.168.2.230";
system(cmd.c_str());
cmd = "/etc/init.d/networking restart";
system(cmd.c_str());
code to share wlan0 with eth0:
cmd = "systemctl stop networking";
system(cmd.c_str());
cmd = "iptables -A FORWARD -o wlan0 -i eth0 -s 192.168.2.0/24 -m conntrack --ctstate NEW -j ACCEPT";
system(cmd.c_str());
cmd = "ptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT";
system(cmd.c_str());
cmd = "iptables -t nat -F POSTROUTING";
system(cmd.c_str());
cmd = "iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE";
system(cmd.c_str());
cmd = "iptables-save | tee /etc/iptables.sav";
system(cmd.c_str());
cmd = "iptables-restore < /etc/iptables.sav";
system(cmd.c_str());
cmd = "sysctl net.ipv4.ip_forward=1";
system(cmd.c_str());
cmd = "ip route add default via 192.168.2.230";
system(cmd.c_str());
cmd = "/etc/init.d/networking restart";
system(cmd.c_str());
If I use one of those codes my connection will be shared with eth0 successfully, but now in some situations I need to switch between wlan0 and eth1 and if I try to use those codes again in my running application I got connection errors the errors I see:
Error: Connection activation failed: (5) IP configuration could not be reserved (no available address, timeout, etc.).
Error in connecting 113 - No route to host
it seems I can not just use the code twice in application while it's running, so what am I doing wrong and how should I do these configurations properly?