In normal environment, when some program use SOCKS as communication protocol with the client, the destination port and IP are stored in the SOCKS header, and then the Tor client include them in the Exit node cell. But if there is no SOCKS and just a iptables rule rewriting the destination port in order to achieve transparent proxy, how the Tor client know which port to put as destination in the cell?
2 Answers
I'm not sure that Linostar's answer is correct. Rather, I think that Tor is able to extract the original destination address using the SO_ORIGINAL_DST socket option, as described here:
How does a transparent SOCKS proxy know which destination IP to use?
This is a very good question indeed, although it is more about how a tranparent proxy and iptables work. The corresponding rule in iptables to redirect to a transparent proxy is usually something like:
iptables -t nat -A OUTPUT -p tcp --syn -j REDIRECT --to-ports <port-number>
What is happening in reality is that NAT Redirect does not change the packet header! It just hands it over, destination IP and port intact, to the service listening in localhost on the port number specified, which happens to be the Tor transparent proxy in this case.