Python twisted.internet.reactor.resolve() Examples

The following are 17 code examples of twisted.internet.reactor.resolve(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.reactor , or try the search function .
Example #1
Source File: ClientRequest.py    From MITMf with GNU General Public License v3.0 6 votes vote down vote up
def resolveHost(self, host):
        address = self.dnsCache.getCachedAddress(host)

        if address != None:
            log.debug("Host cached: {} {}".format(host, address))
            return defer.succeed(address)
        else:
            
            log.debug("Host not cached.")
            self.customResolver.port = self.urlMonitor.getResolverPort()

            try:
                log.debug("Resolving with DNSChef")
                address = str(self.customResolver.query(host)[0].address)
                return defer.succeed(address)
            except Exception:
                log.debug("Exception occured, falling back to Twisted")
                return reactor.resolve(host) 
Example #2
Source File: ClientRequest.py    From piSociEty with GNU General Public License v3.0 6 votes vote down vote up
def resolveHost(self, host):
        address = self.dnsCache.getCachedAddress(host)

        if address != None:
            log.debug("Host cached: {} {}".format(host, address))
            return defer.succeed(address)
        else:
            
            log.debug("Host not cached.")
            self.customResolver.port = self.urlMonitor.getResolverPort()

            try:
                log.debug("Resolving with DNSChef")
                address = str(self.customResolver.query(host)[0].address)
                return defer.succeed(address)
            except Exception:
                log.debug("Exception occured, falling back to Twisted")
                return reactor.resolve(host) 
Example #3
Source File: network.py    From tensor with MIT License 6 votes vote down vote up
def get(self):
        host = self.config.get('destination', self.hostname)

        try:
            ip = yield reactor.resolve(host)
        except:
            ip = None

        if ip:
            try:
                loss, latency = yield icmp.ping(ip, 5)
            except: 
                loss, latency = 100, None

            event = [self.createEvent('ok', '%s%% loss to %s' % (loss,host), loss,
                prefix="loss")]

            if latency:
                event.append(self.createEvent('ok', 'Latency to %s' % host, latency,
                            prefix="latency"))
        else:
            event = [self.createEvent('critical', 'Unable to resolve %s' % host, 100,
                prefix="loss")]

        defer.returnValue(event) 
Example #4
Source File: ipdiscover.py    From p2pool-n with GNU General Public License v3.0 5 votes vote down vote up
def get_local_ip():
    """
    Returns a deferred which will be called with a
    2-uple (lan_flag, ip_address) :
        - lan_flag:
            - True if it's a local network (RFC1918)
            - False if it's a WAN address
        
        - ip_address is the actual ip address
    
    @return: A deferred called with the above defined tuple
    @rtype: L{twisted.internet.defer.Deferred}
    """
    # first we try a connected udp socket, then via multicast
    logging.debug("Resolving dns to get udp ip")
    try:
        ipaddr = yield reactor.resolve('A.ROOT-SERVERS.NET')
    except:
        pass
    else:
        udpprot = DatagramProtocol()
        port = reactor.listenUDP(0, udpprot)
        udpprot.transport.connect(ipaddr, 7)
        localip = udpprot.transport.getHost().host
        port.stopListening()
        
        if is_bogus_ip(localip):
            raise RuntimeError, "Invalid IP address returned"
        else:
            defer.returnValue((is_rfc1918_ip(localip), localip))
    
    logging.debug("Multicast ping to retrieve local IP")
    ipaddr = yield _discover_multicast()
    defer.returnValue((is_rfc1918_ip(ipaddr), ipaddr)) 
Example #5
Source File: ClientRequest.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, channel, queued, reactor=reactor):
        Request.__init__(self, channel, queued)
        self.reactor       = reactor
        self.urlMonitor    = URLMonitor.getInstance()
        self.hsts          = URLMonitor.getInstance().hsts
        self.cookieCleaner = CookieCleaner.getInstance()
        self.dnsCache      = DnsCache.getInstance()
        #self.uniqueId      = random.randint(0, 10000)
        
        #Use are own DNS server instead of reactor.resolve()
        self.customResolver = dns.resolver.Resolver()    
        self.customResolver.nameservers  = ['127.0.0.1'] 
Example #6
Source File: ClientRequest.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def resolveHost(self, host):
        address = self.dnsCache.getCachedAddress(host)

        if address != None:
            log.debug("[ClientRequest] Host cached: {} {}".format(host, address))
            return defer.succeed(address)
        else:
            return reactor.resolve(host) 
Example #7
Source File: kdht.py    From simDHT with MIT License 5 votes vote down vote up
def resolve(self, host, port):
        """解析域名"""

        def callback(ip, port):
            """解析成功后, 开始发送find_node"""
            self.findNode((ip, port))

        def errback(failure, host, port):
            """解析失败, 再继续解析, 直到成功为止"""
            self.resolve(host, port)

        d = reactor.resolve(host)
        d.addCallback(callback, port)
        d.addErrback(errback, host, port) 
Example #8
Source File: kdht.py    From simDHT with MIT License 5 votes vote down vote up
def joinNetwork(self):
        """加入DHT网络"""
        for address in BOOTSTRAP_NODES:
            self.resolve(address[0], address[1])
        reactor.callLater(KRPC_TIMEOUT, self.joinFailHandle) 
Example #9
Source File: test_internet.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testChildResolve(self):
        # I've seen problems with reactor.run under gtk2reactor. Spawn a
        # child which just does reactor.resolve after the reactor has
        # started, fail if it does not complete in a timely fashion.
        helperPath = os.path.abspath(self.mktemp())
        helperFile = open(helperPath, 'w')
        
        # Eeueuuggg
        reactorName = reactor.__module__

        helperFile.write(resolve_helper % {'reactor': reactorName})
        helperFile.close()

        env = os.environ.copy()
        env['PYTHONPATH'] = os.pathsep.join(sys.path)

        helperDeferred = Deferred()
        helperProto = ChildResolveProtocol(helperDeferred)

        reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)

        def cbFinished((reason, output, error)):
            # If the output is "done 127.0.0.1\n" we don't really care what
            # else happened.
            output = ''.join(output)
            if output != 'done 127.0.0.1\n':
                self.fail((
                    "The child process failed to produce the desired results:\n"
                    "   Reason for termination was: %r\n"
                    "   Output stream was: %r\n"
                    "   Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))

        helperDeferred.addCallback(cbFinished)
        return helperDeferred 
Example #10
Source File: tcp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def resolveAddress(self):
        host, port = self.addr
        if isIPAddress(host):
            return self.addr
        else:
            from twisted.internet import reactor
            return reactor.resolve(host).addCallback(self._filterRealAddress) 
Example #11
Source File: test_internet.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testChildResolve(self):
        # I've seen problems with reactor.run under gtk2reactor. Spawn a
        # child which just does reactor.resolve after the reactor has
        # started, fail if it does not complete in a timely fashion.
        helperPath = os.path.abspath(self.mktemp())
        helperFile = open(helperPath, 'w')

        # Eeueuuggg
        reactorName = reactor.__module__

        helperFile.write(resolve_helper % {'reactor': reactorName})
        helperFile.close()

        env = os.environ.copy()
        env['PYTHONPATH'] = os.pathsep.join(sys.path)

        helperDeferred = Deferred()
        helperProto = ChildResolveProtocol(helperDeferred)

        reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)

        def cbFinished((reason, output, error)):
            # If the output is "done 127.0.0.1\n" we don't really care what
            # else happened.
            output = ''.join(output)
            if output != 'done 127.0.0.1\n':
                self.fail((
                    "The child process failed to produce the desired results:\n"
                    "   Reason for termination was: %r\n"
                    "   Output stream was: %r\n"
                    "   Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))

        helperDeferred.addCallback(cbFinished)
        return helperDeferred 
Example #12
Source File: ClientRequest.py    From 3vilTwinAttacker with MIT License 5 votes vote down vote up
def resolveHost(self, host):
        address = self.dnsCache.getCachedAddress(host)

        if address != None:
            logging.debug("Host cached.")
            return defer.succeed(address)
        else:
            logging.debug("Host not cached.")
            return reactor.resolve(host) 
Example #13
Source File: riemann.py    From tensor with MIT License 5 votes vote down vote up
def createClient(self):
        """Create a UDP connection to Riemann"""
        server = self.config.get('server', '127.0.0.1')
        port = self.config.get('port', 5555)

        def connect(ip):
            self.protocol = riemann.RiemannUDP(ip, port)
            self.endpoint = reactor.listenUDP(0, self.protocol)

        d = reactor.resolve(server)
        d.addCallback(connect)
        return d 
Example #14
Source File: ClientRequest.py    From piSociEty with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, channel, queued, reactor=reactor):
        Request.__init__(self, channel, queued)
        self.reactor       = reactor
        self.urlMonitor    = URLMonitor.getInstance()
        self.hsts          = URLMonitor.getInstance().hsts
        self.cookieCleaner = CookieCleaner.getInstance()
        self.dnsCache      = DnsCache.getInstance()
        #self.uniqueId      = random.randint(0, 10000)
        
        #Use are own DNS server instead of reactor.resolve()
        self.customResolver = dns.resolver.Resolver()    
        self.customResolver.nameservers  = ['127.0.0.1'] 
Example #15
Source File: ClientRequest.py    From piSociEty with GNU General Public License v3.0 5 votes vote down vote up
def resolveHost(self, host):
        address = self.dnsCache.getCachedAddress(host)

        if address != None:
            log.debug("[ClientRequest] Host cached: {} {}".format(host, address))
            return defer.succeed(address)
        else:
            return reactor.resolve(host) 
Example #16
Source File: test_internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def testChildResolve(self):
        # I've seen problems with reactor.run under gtk2reactor. Spawn a
        # child which just does reactor.resolve after the reactor has
        # started, fail if it does not complete in a timely fashion.
        helperPath = os.path.abspath(self.mktemp())
        with open(helperPath, 'w') as helperFile:

            # Eeueuuggg
            reactorName = reactor.__module__

            helperFile.write(resolve_helper % {'reactor': reactorName})

        env = os.environ.copy()
        env['PYTHONPATH'] = os.pathsep.join(sys.path)

        helperDeferred = Deferred()
        helperProto = ChildResolveProtocol(helperDeferred)

        reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)

        def cbFinished(result):
            (reason, output, error) = result
            # If the output is "done 127.0.0.1\n" we don't really care what
            # else happened.
            output = b''.join(output)
            if _PY3:
                expected_output = (b'done 127.0.0.1' +
                                   os.linesep.encode("ascii"))
            else:
                expected_output = b'done 127.0.0.1\n'
            if output != expected_output:
                self.fail((
                    "The child process failed to produce the desired results:\n"
                    "   Reason for termination was: %r\n"
                    "   Output stream was: %r\n"
                    "   Error stream was: %r\n") % (reason.getErrorMessage(), output, b''.join(error)))

        helperDeferred.addCallback(cbFinished)
        return helperDeferred 
Example #17
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def testChildResolve(self):
        # I've seen problems with reactor.run under gtk2reactor. Spawn a
        # child which just does reactor.resolve after the reactor has
        # started, fail if it does not complete in a timely fashion.
        helperPath = os.path.abspath(self.mktemp())
        with open(helperPath, 'w') as helperFile:

            # Eeueuuggg
            reactorName = reactor.__module__

            helperFile.write(resolve_helper % {'reactor': reactorName})

        env = os.environ.copy()
        env['PYTHONPATH'] = os.pathsep.join(sys.path)

        helperDeferred = Deferred()
        helperProto = ChildResolveProtocol(helperDeferred)

        reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)

        def cbFinished(result):
            (reason, output, error) = result
            # If the output is "done 127.0.0.1\n" we don't really care what
            # else happened.
            output = b''.join(output)
            if _PY3:
                expected_output = (b'done 127.0.0.1' +
                                   os.linesep.encode("ascii"))
            else:
                expected_output = b'done 127.0.0.1\n'
            if output != expected_output:
                self.fail((
                    "The child process failed to produce the desired results:\n"
                    "   Reason for termination was: %r\n"
                    "   Output stream was: %r\n"
                    "   Error stream was: %r\n") % (reason.getErrorMessage(), output, b''.join(error)))

        helperDeferred.addCallback(cbFinished)
        return helperDeferred