【发布时间】:2020-10-19 13:20:36
【问题描述】:
我已经编写了一个 c++ 代码,用于从 wlan0 或 eth1 与 eth0 共享互联网,并且代码可以正常工作。
与 eth0 共享 eth1 的代码:
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());
与 eth0 共享 wlan0 的代码:
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());
如果我使用其中一个代码,我的连接将与 eth0 成功共享,但现在在某些情况下,我需要在 wlan0 和 eth1 之间切换,如果我尝试在正在运行的应用程序中再次使用这些代码,我会遇到连接错误我看到的错误:
Error: Connection activation failed: (5) IP configuration could not be reserved (no available address, timeout, etc.).
Error in connecting 113 - No route to host
似乎我不能在应用程序运行时只在应用程序中使用两次代码,那么我做错了什么,我应该如何正确地进行这些配置?
【问题讨论】:
-
你为什么用C++写这样的代码?为什么不创建一个可以直接使用命令的 shell 脚本呢?如果出于某种原因需要从 C++ 程序调用它,请改为调用 shell 脚本。
-
投票将其迁移到 superuser.SE,因为这个问题也会出现在 shell 脚本中。
标签: c++ c linux ubuntu iptables