Search code examples
javahttptcpproxytor

Send Tor NEWNYM request using Java


My application uses Tor successfully, but I would like to send a NEWNYM request to obtain a new identity. I could kill and restart the process, or possibly use a shell script, but I'd prefer to do it in native Java.

There is a Python solution, but I'm not quite sure how to map it to Java connection types. I imagine it's fairly similar to my Tor HTTP code, but I'm not familiar enough with Java connection types to make it happen.

// My starter code.
public static String torNewIP() throws Exception {
   Proxy proxy = new Proxy(Proxy.Type.HTTP, 
              new InetSocketAddress(TOR_IP, TOR_CONTROL_PORT));     
   // This is how I open a web page using Tor, but the control
   // port is probably not HTTP.
   // HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
   // connection.connect();
   // Something like connection.send("NEWNYM");
}   

Solution

  • Double check to make sure Tor is run with the option ControlPort [TOR_CONTROL_PORT]

    public static void torNewIP() throws Exception {
       Socket socket = new Socket();
       socket.connect(new InetSocketAddress(TOR_IP, TOR_CONTROL_PORT));
       socket.getOutputStream().write(new String("SIGNAL NEWNYM\r\n").getBytes());
       socket.close();
    }
    

    Not entirely sure why, but it may take some time to function as expected - perhaps the 10 minute IP rotation. Sorry I can't provide better details, but it worked for me.