Search code examples
javascriptnode.jsweb-scrapingtor

Why tor-request dont't update ip in loop


I have following code:

var tr = require('tor-request');
tr.TorControlPort.password = '***'

tr.request('https://api.ipify.org', (err, resp, ip) => {
    console.log('initial ip: ' + ip)
})

function torRequest() {
    tr.renewTorSession((err, msg) => {
        console.log(msg);
        tr.request('https://api.ipify.org', (err, resp, ip) => {
            console.log('ip: ' + ip)
        })
    })
}

torRequest();

for ( let i = 0; i < 2; i++) {
    torRequest();
}

And my output:

Tor session successfully renewed!!
Tor session successfully renewed!!
Tor session successfully renewed!!
ip: 46.165.245.154
ip: 46.165.245.154
ip: 46.165.245.154
initial ip: 176.10.107.180

When I call torRequest more than once, all requests will return with the same ip. Is it possible to run it in the loop?


Solution

  • You need to explicitly refresh the tor's session

    tr.newTorSession( (err) =>
    {
        requestIP();
        return;
    });
    

    Also add this

    tr.setTorAddress('localhost', 9050);
    

    after

    tr.TorControlPort.password = '***'
    

    newTorSessio :

    module.exports = {
    // <snip>
    
      /**
       * Helper object to communicate with the tor ControlPort. Requires an enabled ControlPort on tor.
       */
      TorControlPort: {
        password: "", // default ControlPort password
        host: "localhost", // default address
        port: 9051, // default ControlPort
        
        /**
         * @param {Array.string} commands - signals that are sent to the ControlPort
         */
        send: function (commands, done(err, data))
      }
      
      /**
       * A set of predefined TorControlPort commands to request and verify tor for a new session (get a new ip to use).
       *
       * @param {function} done - the callback function to tell you when the process is done
       * @param {object} err - null if tor session renewed successfully
       */
      newTorSession: function ( done(err) ) // clears and renews the Tor session (i.e., you get a new IP)
      
    
    }
    

    that's it .. it will work.. in my case .. IP will be updated after 5-6 times

    Good luck,'.