I have seen this used in many android based projects like "ProxyDroid" & "SSHTunnel"
Where you establish a connection to a proxy or ssh tunnel then using iptables it will redirect all tcp requests through the tunnel you have created.
It should be something like "-I OUTPUT -p tcp --destination-not xxx.xxx.xx.xx --redirect-to xx.xxx.xx.xx:port" but I couldn't find any examples on this and I don't know if it should be inserted to nat or something else + I have no idea if I should have more than 1 rule for e.g: one more for incoming connections.
Appears to be it's not possible to use the tunnel directly Or I haven't find out how to do it without using an agent, I had to install a program called redsocks to act as a local server to make this work.
As for the iptables commands used here it is:
# do not redirect connection sent to localhost so redirected connections can reach # its destination, otherwise we'll stuck in a loop. iptables -t nat -A OUTPUT -d 127.0.0.0/8 -j ACCEPT # Redirect all tcp connections except ones that are going to my tunnel server # to the local redsocks port iptables -t nat -A OUTPUT -p tcp ! -d tunnel.ip.goes.here -j REDIRECT --to-ports 31338
RedSocks Repo: https://github.com/darkk/redsocks
Now everything works great, but I still need to know if this can be accomplished without the redsocks (connecting to tunnel directly).