Search code examples
pythontor

stem - can't get new ip with python via tor


I'm trying to get a new IP in a tor session using stem and the following function which is heavily 'inspired' by this answer:

def get_new_IP():
    socket.socket = old_socket
    with Controller.from_port(port=SOCKS_PORT) as controller:
        controller.authenticate()
        controller.signal(Signal.NEWNYM)
    socket.socket = socks.socksocket

However I get the error 'IncorrectSocketType: unable to use the control socket' raised by controller.authenticate() which leaves me a little lost since there is no password or anything specified and the initial connection I set up works too.

I have also tried to add 'CookieAuthentication': str(1), as suggested here, to the config settings when starting the tor process, however that didn't work either.

How come that the initial connection works and why can't I get authenticated when I try to reconnect?


Solution

  • The Controller.from_port() should be connecting to the ControlPort rather than the SocksPort as defined in your torrc (the ControlPort is what Stem talks with, and the SocksPort is what applications using tor like Firefox uses).

    https://stem.torproject.org/tutorials/the_little_relay_that_could.html

    As discussed in the FAQ about this please show some restraint since cycling IPs puts a strain on the network...

    https://stem.torproject.org/faq.html#how-do-i-request-a-new-identity-from-tor