[tor-relays] How to get client locale statistics without arm?

Damian Johnson atagar at torproject.org
Fri Nov 30 03:24:06 UTC 2012

> Doing netstat queries means that I get 80000+ ip addresses on my server.
> Each of these addresses I would have to check against the list of relays to
> sort out connections to other relays and only do GETINFO ip-to-country to
> the remaining IPs. This sounds complicated and error-prone.

Not really. Does this do the trick?


from stem.control import Controller
from stem.util import system

TOR_PID = "3470" # fill this in!

def get_tor_connections():
  Provides the (ip address, port) tuples for tor's connections.

  results = []
  netstat_output = system.call("netstat -np")
  established_entry = "ESTABLISHED %s/tor" % TOR_PID

  for line in netstat_output:
    if established_entry in line:
      ip, port = line.split()[4].split(':')
      results.append((ip, port))

  return results

with Controller.from_port(control_port = 9051) as controller:
  relay_ips = set([desc.address for desc in controller.get_network_statuses()])

  for ip, port in get_tor_connections():
    if ip not in relay_ips:
      locale = controller.get_info('ip-to-country/%s' % ip)
      print 'exit connection to %s' % locale

More information about the tor-relays mailing list