DnsClient.py 944 Bytes
"""
get our current external IP via HTTP

@author Georg Hopp

@copyright (C) 2014 Copperfasten Technologies
"""
import struct

from SimpleClient import SimpleClient
from Protocol.Dns.Dns import Dns
from Communication.DatagramService import DatagramService
from Transport.UdpSocket import UdpSocket

class DnsClient(object):
    def __init__(self, host, port):
        self._proto  = Dns()
        self._client = SimpleClient(
            DatagramService(UdpSocket(host, port), self._proto)
        )

    def getIp(self, name, timeout=3.0):
        request  = self._proto.createRequest(self._client.getRemoteAddr())
        request.addQuery(name)
        response = self._client.issue(request, timeout)

        if not response or not response._answers:
            raise Exception('no valid response')

        return '.'.join('%d'%i 
                        for i in struct.unpack(
                            '4B', response._answers[0][4]))