I have few more thoughts to share to possibly improve further the code of this function. Here is my setup:
I have 1 tor proxy configured on a single machine in my LAN. It is on 192.168.1.2. This allows me to share a single tor proxy instance among all the trusted machines inside my LAN.
Bitcoind is running on a different machine: 192.168.1.179.
My first attempt to make torcontrol available for bitcoind was to bind the control listening socket to 192.168.1.2:9051.
It works except that tor is complaining big time that this is opening a security risk as the control protocol exchange is in clear text over the network.
To fix that, I did create a SSH tunnel between the 2 machines 127.0.0.1:9051.
What that means is that when I start bitcoind from 192.168.1.179 machine with the cmdline:
-proxy 192.168.1.2:9050 -torcontrol 127.0.0.1:9051
When bitcoind connects with torcontrol, despite it is a localhost address, it does actually connect to a remote server.
What all this means for this commit?
Well, it favors the tor proxy address 127.0.0.1. With my setup, it will fail.
The first solution to address this issue that came to my mind is to test that 127.0.0.1:9050 is listening but this is clumsy, there is no simple and portable way to check that beside actually connect a socket to the address…
Then, I did ask myself the following question:
What are exactly the benefits of connecting to the localhost proxy address if present?
I am not sure if there is any.
OTOH, if you connect to the first public IP address listed in the reply, it will work with the most common case where the proxy is on the same machine and it will also work on more funky setups like mine…
How do you feel toward this suggestion? Does that makes sense to you?