From d889c93f282eb25449510fc18e6084235876e260 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 7 Aug 2015 12:42:59 +0200 Subject: [PATCH] respondc.py --- lib/respondc.py | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 lib/respondc.py diff --git a/lib/respondc.py b/lib/respondc.py new file mode 100644 index 0000000..7062b49 --- /dev/null +++ b/lib/respondc.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +import socket +import zlib +import json +import sys + +def request(ifname, request, target='ff02::2', timeout=0.5, singleshot=False): + try: + if_id = socket.if_nametoindex(ifname) + except OSError: + print('interface \'{}\' not found'.format(sys.argv[1]), file=sys.stderr) + return [] + + sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) + + # request + message = bytes('GET {}'.format(request), 'utf-8') + sock.sendto(message, (target, 1001, 0, if_id)) + + print('+ {:s}'.format(str(message)), file=sys.stderr) + + sock.settimeout(timeout) + + # receive + responses = {} + rsp, err = 0, 0 + while True: + print('\r+ {rsp} responses, {err} errors'.format(**locals()), end='', file=sys.stderr) + + try: + buffer, address = sock.recvfrom(2048) + except socket.timeout: + print('\n+ no replies for %f seconds, continuing...' % timeout, file=sys.stderr) + break + + try: + source = address[0].split('%')[0] + data = zlib.decompress(buffer, -15) + nodeinfo = json.loads(data.decode('utf-8')) + responses[source] = nodeinfo + rsp += 1 + except (zlib.error, UnicodeDecodeError, ValueError): + err += 1 + print('- unreadable answer from {addr}'.format(addr=source), file=sys.stderr) + + if singleshot: + break + + return responses.values() +