Python socket.sendto() Examples

The following are code examples for showing how to use socket.sendto(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: aqara-mqtt   Author: monster1025   File: xiaomihub.py    (license) View Source Project 6 votes vote down vote up
def _send_socket(self, cmd, rtnCmd, ip, port):
        socket = self._socket
        try:
            _LOGGER.debug('Sending to GW {0}'.format(cmd))
            self._read_unwanted_data()

            socket.settimeout(30.0)
            socket.sendto(cmd.encode(), (ip, port))
            socket.settimeout(30.0)
            data, addr = socket.recvfrom(1024)
            if len(data) is not None:
                resp = json.loads(data.decode())
                _LOGGER.debug('Recieved from GW {0}'.format(resp))
                if resp["cmd"] == rtnCmd:
                    return resp
                else:
                    _LOGGER.error("Response from {0} does not match return cmd".format(ip))
                    _LOGGER.error(data)
            else:
                _LOGGER.error("No response from Gateway")
        except socket.timeout:
            _LOGGER.error("Cannot connect to Gateway")
            socket.close() 
Example 2
Project: 2016.2-SME_UnB   Author: fga-gpp-mds   File: models.py    (license) View Source Project 6 votes vote down vote up
def _thread_data_collection(self,
                                socket,
                                messages_to_send,
                                alarm):
        messages = []

        for i in range(len(messages_to_send)):
            socket.sendto(messages_to_send[i],
                          (self.transductor.ip_address, self.port))
            message_received = socket.recvfrom(256)

            messages.append(message_received[0])
            # alarm.observe('new data received', alarm.verify_voltage)
            # Event('new data received', value)

        collection_time = timezone.now()
        self._create_measurements_from_data_collected(messages,
                                                      collection_time) 
Example 3
Project: flare-fakenet-ng   Author: fireeye   File: RawListener.py    (license) View Source Project 6 votes vote down vote up
def handle(self):

        try:
            (data,socket) = self.request
            
            if not data:
                return

            self.server.logger.info('Received %d bytes.', len(data))
            self.server.logger.debug('%s', '-'*80,)
            for line in hexdump_table(data):
                self.server.logger.debug(line)
            self.server.logger.debug('%s', '-'*80,)

            socket.sendto(data, self.client_address)

        except socket.error as msg:
            self.server.logger.error('Error: %s', msg.strerror or msg)

        except Exception, e:
            self.server.logger.error('Error: %s', e) 
Example 4
Project: flare-fakenet-ng   Author: fireeye   File: TFTPListener.py    (license) View Source Project 6 votes vote down vote up
def handle_data(self, socket, data):

            block_num = struct.unpack('!H', data[2:4])[0]

            if hasattr(self.server, 'filename_path') and self.server.filename_path:

                safe_file = self.server.tftp_file_prefix + "_" + urllib.quote(self.server.filename_path, '')
                output_file = ListenerBase.safe_join(os.getcwd(),
                                                          safe_file)
                f = open(output_file, 'ab')
                f.write(data[4:])
                f.close()

                # Send ACK packet for the given block number
                ack_packet = OPCODE_ACK + data[2:4]
                socket.sendto(ack_packet, self.client_address)

            else:
                self.server.logger.error('Received DATA packet but don\'t know where to store it.') 
Example 5
Project: break-fast-serial   Author: GoSecure   File: dnschef.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        (data,socket) = self.request
        response = self.parse(data)
        
        if response:
            socket.sendto(response, self.client_address)

# TCP DNS Handler for incoming requests 
Example 6
Project: mitmfnz   Author: dropnz   File: NBTNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):

		data, socket = self.request
		Name = Decode_Name(data[13:45])

		# Break out if we don't want to respond to this host
		if RespondToThisHost(self.client_address[0], Name) is not True:
			return None

		if data[2:4] == "\x01\x10":

			if settings.Config.Finger_On_Off:
				Finger = fingerprint.RunSmbFinger((self.client_address[0],445))
			else:
				Finger = None

			# Analyze Mode
			if settings.Config.AnalyzeMode:
				settings.Config.AnalyzeLogger.warning("{} [Analyze mode: NBT-NS] Request for {}, ignoring".format(self.client_address[0], Name))

			# Poisoning Mode
			else:
				Buffer = NBT_Ans()
				Buffer.calculate(data)
				socket.sendto(str(Buffer), self.client_address)

				settings.Config.PoisonersLogger.warning("{} [NBT-NS] Poisoned answer for name {} (service: {})" .format(self.client_address[0], Name, NBT_NS_Role(data[43:46])))

			if Finger is not None:
				settings.Config.ResponderLogger.info("[FINGER] OS Version     : {}".format(Finger[0]))
				settings.Config.ResponderLogger.info("[FINGER] Client Version : {}".format(Finger[1])) 
Example 7
Project: mitmfnz   Author: dropnz   File: DNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        (data,socket) = self.request
        response = self.parse(data)
        
        if response:
            socket.sendto(response, self.client_address)

# TCP DNS Handler for incoming requests 
Example 8
Project: piSociEty   Author: paranoidninja   File: NBTNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):

		data, socket = self.request
		Name = Decode_Name(data[13:45])

		# Break out if we don't want to respond to this host
		if RespondToThisHost(self.client_address[0], Name) is not True:
			return None

		if data[2:4] == "\x01\x10":

			if settings.Config.Finger_On_Off:
				Finger = fingerprint.RunSmbFinger((self.client_address[0],445))
			else:
				Finger = None

			# Analyze Mode
			if settings.Config.AnalyzeMode:
				settings.Config.AnalyzeLogger.warning("{} [Analyze mode: NBT-NS] Request for {}, ignoring".format(self.client_address[0], Name))

			# Poisoning Mode
			else:
				Buffer = NBT_Ans()
				Buffer.calculate(data)
				socket.sendto(str(Buffer), self.client_address)

				settings.Config.PoisonersLogger.warning("{} [NBT-NS] Poisoned answer for name {} (service: {})" .format(self.client_address[0], Name, NBT_NS_Role(data[43:46])))

			if Finger is not None:
				settings.Config.ResponderLogger.info("[FINGER] OS Version     : {}".format(Finger[0]))
				settings.Config.ResponderLogger.info("[FINGER] Client Version : {}".format(Finger[1])) 
Example 9
Project: piSociEty   Author: paranoidninja   File: DNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        (data,socket) = self.request
        response = self.parse(data)
        
        if response:
            socket.sendto(response, self.client_address)

# TCP DNS Handler for incoming requests 
Example 10
Project: aiotk   Author: AndreLouisCaron   File: _udp.py    (license) View Source Project 5 votes vote down vote up
def udp_writer(socket, oqueue):
    """Forward packets to the UDP socket."""

    while True:
        peer, data = await oqueue.get()
        try:
            socket.sendto(data, peer)
        finally:
            oqueue.task_done() 
Example 11
Project: mitmf   Author: ParrotSec   File: NBTNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):

		data, socket = self.request
		Name = Decode_Name(data[13:45])

		# Break out if we don't want to respond to this host
		if RespondToThisHost(self.client_address[0], Name) is not True:
			return None

		if data[2:4] == "\x01\x10":

			if settings.Config.Finger_On_Off:
				Finger = fingerprint.RunSmbFinger((self.client_address[0],445))
			else:
				Finger = None

			# Analyze Mode
			if settings.Config.AnalyzeMode:
				settings.Config.AnalyzeLogger.warning("{} [Analyze mode: NBT-NS] Request for {}, ignoring".format(self.client_address[0], Name))

			# Poisoning Mode
			else:
				Buffer = NBT_Ans()
				Buffer.calculate(data)
				socket.sendto(str(Buffer), self.client_address)

				settings.Config.PoisonersLogger.warning("{} [NBT-NS] Poisoned answer for name {} (service: {})" .format(self.client_address[0], Name, NBT_NS_Role(data[43:46])))

			if Finger is not None:
				settings.Config.ResponderLogger.info("[FINGER] OS Version     : {}".format(Finger[0]))
				settings.Config.ResponderLogger.info("[FINGER] Client Version : {}".format(Finger[1])) 
Example 12
Project: mitmf   Author: ParrotSec   File: DNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        (data,socket) = self.request
        response = self.parse(data)
        
        if response:
            socket.sendto(response, self.client_address)

# TCP DNS Handler for incoming requests 
Example 13
Project: aioping   Author: stellarbit   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def sendto_ready(packet, socket, future, dest):
    socket.sendto(packet, dest)
    asyncio.get_event_loop().remove_writer(socket)
    future.set_result(None) 
Example 14
Project: SEF   Author: ahmadnourallah   File: NBTNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):

		data, socket = self.request
		Name = Decode_Name(data[13:45])

		# Break out if we don't want to respond to this host
		if RespondToThisHost(self.client_address[0], Name) is not True:
			return None

		if data[2:4] == "\x01\x10":

			if settings.Config.Finger_On_Off:
				Finger = fingerprint.RunSmbFinger((self.client_address[0],445))
			else:
				Finger = None

			# Analyze Mode
			if settings.Config.AnalyzeMode:
				settings.Config.AnalyzeLogger.warning("{} [Analyze mode: NBT-NS] Request for {}, ignoring".format(self.client_address[0], Name))

			# Poisoning Mode
			else:
				Buffer = NBT_Ans()
				Buffer.calculate(data)
				socket.sendto(str(Buffer), self.client_address)

				settings.Config.PoisonersLogger.warning("{} [NBT-NS] Poisoned answer for name {} (service: {})" .format(self.client_address[0], Name, NBT_NS_Role(data[43:46])))

			if Finger is not None:
				settings.Config.ResponderLogger.info("[FINGER] OS Version     : {}".format(Finger[0]))
				settings.Config.ResponderLogger.info("[FINGER] Client Version : {}".format(Finger[1])) 
Example 15
Project: SEF   Author: ahmadnourallah   File: DNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        (data,socket) = self.request
        response = self.parse(data)
        
        if response:
            socket.sendto(response, self.client_address)

# TCP DNS Handler for incoming requests 
Example 16
Project: SEF   Author: ahmadnourallah   File: Responder.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        data, soc = self.request
        if self.client_address[0] == "127.0.0.1":
            pass
        elif ParseDNSType(data):
            buff = DNSAns()
            buff.calculate(data)
            soc.sendto(str(buff), self.client_address)
            print "DNS Answer sent to: %s "%(self.client_address[0])
            logging.warning('DNS Answer sent to: %s'%(self.client_address[0])) 
Example 17
Project: SEF   Author: ahmadnourallah   File: Responder.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        MADDR = "224.0.0.251"
        MPORT = 5353
        data, soc = self.request
        if self.client_address[0] == "127.0.0.1":
            pass
        try:
            if Analyze(AnalyzeMode):
                if Parse_IPV6_Addr(data):
                    print '[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data))
                    logging.warning('[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data)))

            if RespondToSpecificHost(RespondTo):
                if Analyze(AnalyzeMode) == False:
                    if RespondToIPScope(RespondTo, self.client_address[0]):
                        if Parse_IPV6_Addr(data):
                            print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))
                            logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)))
                            Name = Poisoned_MDNS_Name(data)
                            MDns = MDNSAns(AnswerName = Name)
                            MDns.calculate()
                            soc.sendto(str(MDns),(MADDR,MPORT))

            if Analyze(AnalyzeMode) == False and RespondToSpecificHost(RespondTo) == False:
                if Parse_IPV6_Addr(data):
                    print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))
                    logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)))
                    Name = Poisoned_MDNS_Name(data)
                    MDns = MDNSAns(AnswerName = Name)
                    MDns.calculate()
                    soc.sendto(str(MDns),(MADDR,MPORT))
            else:
                pass
        except Exception:
            raise

##################################################################################
#HTTP Stuff
################################################################################## 
Example 18
Project: tobii   Author: cmu-sei   File: livestream.py    (license) View Source Project 5 votes vote down vote up
def send_keepalive_msg(socket, msg, peer):
    while running:
        socket.sendto(bytes(msg, 'UTF-8'), peer)
        time.sleep(timeout) 
Example 19
Project: tobii   Author: cmu-sei   File: gazePub.py    (license) View Source Project 5 votes vote down vote up
def send_keepalive_msg(socket, msg, peer):
    while running:
        socket.sendto(str.encode(msg), peer)
        time.sleep(timeout) 
Example 20
Project: 2016.2-SME_UnB   Author: fga-gpp-mds   File: test_udp_protocol.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]

        if data == 'Request 1':
            response = 'Response 1'
            socket.sendto(response, self.client_address)
        elif data == 'Request 2':
            response = 'Response 2'
            socket.sendto(response, self.client_address)
        else:
            pass 
Example 21
Project: llama   Author: dropbox   File: udp.py    (license) View Source Project 5 votes vote down vote up
def tos_sendto(self, ip, port):
        """Mimic the behavior of socket.sendto() with special behavior.

        Note: Data is excluded from arguments since we encode our own.

        Args:
            ip: (str) destination IP address
            port: (int) destination UDP port

        Returns:
            (int) the number of bytes sent on the socket
        """
        return self.sendto(struct.pack(self.FORMAT, self.SIGNATURE, self._tos,
                                       time.time() * 1000, 0, 0, False),
                           (ip, port)) 
Example 22
Project: llama   Author: dropbox   File: udp.py    (license) View Source Project 5 votes vote down vote up
def tos_reflect(self, bufsize=512):
        """Intended to be the sole operation on a LLAMA reflector.

        Args:
            bufsize: (int) number of bytes to read from socket
                     It's not advisable to change this.
        """
        data, addr = self.recvfrom(bufsize)
        try:
            udpdata = UdpData._make(struct.unpack(self.FORMAT, data))
        except struct.error:
            logging.warn('Received malformed datagram of %s bytes. '
                         'Discarding.', len(data))
            # Don't reflect invalid data
            return
        self.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, udpdata.tos)
        self.sendto(data, addr)
        self.processed += 1
        if self.processed % 512 == 0:
            logging.info('Processed packets: %s', self.processed) 
Example 23
Project: flare-fakenet-ng   Author: fireeye   File: TFTPListener.py    (license) View Source Project 5 votes vote down vote up
def handle_rrq(self, socket, filename):

        filename_path = ListenerBase.safe_join(self.server.tftproot_path,
                                                    filename)

        # If virtual filename does not exist return a default file based on extention
        if not os.path.isfile(filename_path):

            file_basename, file_extension = os.path.splitext(filename)

            # Calculate absolute path to a fake file
            filename_path = ListenerBase.safe_join(self.server.tftproot_path,
                                                        EXT_FILE_RESPONSE.get(file_extension.lower(), u'FakeNetMini.exe'))


        self.server.logger.debug('Sending file %s', filename_path)

        f = open(filename_path, 'rb')

        i = 1

        while True:

            # Read in a buffer of blocksize from the file
            data_block = f.read(BLOCKSIZE)

            if not data_block or len(data_block) == 0:
                break

            data_packet = OPCODE_DATA + struct.pack('!H', i) + data_block
            socket.sendto(data_packet, self.client_address)

            i += 1

        f.close() 
Example 24
Project: flare-fakenet-ng   Author: fireeye   File: TFTPListener.py    (license) View Source Project 5 votes vote down vote up
def handle_wrq(self, socket, filename):

        self.server.filename_path = filename

        # Send acknowledgement so the client will begin writing
        ack_packet = OPCODE_ACK + "\x00\x00"
        socket.sendto(ack_packet, self.client_address) 
Example 25
Project: SEF   Author: hossamhasanin   File: NBTNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):

		data, socket = self.request
		Name = Decode_Name(data[13:45])

		# Break out if we don't want to respond to this host
		if RespondToThisHost(self.client_address[0], Name) is not True:
			return None

		if data[2:4] == "\x01\x10":

			if settings.Config.Finger_On_Off:
				Finger = fingerprint.RunSmbFinger((self.client_address[0],445))
			else:
				Finger = None

			# Analyze Mode
			if settings.Config.AnalyzeMode:
				settings.Config.AnalyzeLogger.warning("{} [Analyze mode: NBT-NS] Request for {}, ignoring".format(self.client_address[0], Name))

			# Poisoning Mode
			else:
				Buffer = NBT_Ans()
				Buffer.calculate(data)
				socket.sendto(str(Buffer), self.client_address)

				settings.Config.PoisonersLogger.warning("{} [NBT-NS] Poisoned answer for name {} (service: {})" .format(self.client_address[0], Name, NBT_NS_Role(data[43:46])))

			if Finger is not None:
				settings.Config.ResponderLogger.info("[FINGER] OS Version     : {}".format(Finger[0]))
				settings.Config.ResponderLogger.info("[FINGER] Client Version : {}".format(Finger[1])) 
Example 26
Project: SEF   Author: hossamhasanin   File: DNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        (data,socket) = self.request
        response = self.parse(data)
        
        if response:
            socket.sendto(response, self.client_address)

# TCP DNS Handler for incoming requests 
Example 27
Project: SEF   Author: hossamhasanin   File: Responder.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        data, soc = self.request
        if self.client_address[0] == "127.0.0.1":
            pass
        elif ParseDNSType(data):
            buff = DNSAns()
            buff.calculate(data)
            soc.sendto(str(buff), self.client_address)
            print "DNS Answer sent to: %s "%(self.client_address[0])
            logging.warning('DNS Answer sent to: %s'%(self.client_address[0])) 
Example 28
Project: SEF   Author: hossamhasanin   File: Responder.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        MADDR = "224.0.0.251"
        MPORT = 5353
        data, soc = self.request
        if self.client_address[0] == "127.0.0.1":
            pass
        try:
            if Analyze(AnalyzeMode):
                if Parse_IPV6_Addr(data):
                    print '[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data))
                    logging.warning('[Analyze mode: MDNS] Host: %s is looking for : %s'%(self.client_address[0],Parse_MDNS_Name(data)))

            if RespondToSpecificHost(RespondTo):
                if Analyze(AnalyzeMode) == False:
                    if RespondToIPScope(RespondTo, self.client_address[0]):
                        if Parse_IPV6_Addr(data):
                            print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))
                            logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)))
                            Name = Poisoned_MDNS_Name(data)
                            MDns = MDNSAns(AnswerName = Name)
                            MDns.calculate()
                            soc.sendto(str(MDns),(MADDR,MPORT))

            if Analyze(AnalyzeMode) == False and RespondToSpecificHost(RespondTo) == False:
                if Parse_IPV6_Addr(data):
                    print 'MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data))
                    logging.warning('MDNS poisoned answer sent to this IP: %s. The requested name was : %s'%(self.client_address[0],Parse_MDNS_Name(data)))
                    Name = Poisoned_MDNS_Name(data)
                    MDns = MDNSAns(AnswerName = Name)
                    MDns.calculate()
                    soc.sendto(str(MDns),(MADDR,MPORT))
            else:
                pass
        except Exception:
            raise

##################################################################################
#HTTP Stuff
################################################################################## 
Example 29
Project: MITMf   Author: wi-fi-analyzer   File: NBTNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):

		data, socket = self.request
		Name = Decode_Name(data[13:45])

		# Break out if we don't want to respond to this host
		if RespondToThisHost(self.client_address[0], Name) is not True:
			return None

		if data[2:4] == "\x01\x10":

			if settings.Config.Finger_On_Off:
				Finger = fingerprint.RunSmbFinger((self.client_address[0],445))
			else:
				Finger = None

			# Analyze Mode
			if settings.Config.AnalyzeMode:
				settings.Config.AnalyzeLogger.warning("{} [Analyze mode: NBT-NS] Request for {}, ignoring".format(self.client_address[0], Name))

			# Poisoning Mode
			else:
				Buffer = NBT_Ans()
				Buffer.calculate(data)
				socket.sendto(str(Buffer), self.client_address)

				settings.Config.PoisonersLogger.warning("{} [NBT-NS] Poisoned answer for name {} (service: {})" .format(self.client_address[0], Name, NBT_NS_Role(data[43:46])))

			if Finger is not None:
				settings.Config.ResponderLogger.info("[FINGER] OS Version     : {}".format(Finger[0]))
				settings.Config.ResponderLogger.info("[FINGER] Client Version : {}".format(Finger[1])) 
Example 30
Project: MITMf   Author: wi-fi-analyzer   File: DNS.py    (license) View Source Project 5 votes vote down vote up
def handle(self):
        (data,socket) = self.request
        response = self.parse(data)
        
        if response:
            socket.sendto(response, self.client_address)

# TCP DNS Handler for incoming requests 
Example 31
Project: break-fast-serial   Author: GoSecure   File: dnschef.py    (license) View Source Project 4 votes vote down vote up
def proxyrequest(self, request, host, port="53", protocol="udp"):
        reply = None
        try:
            if self.server.ipv6:

                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

            else:
                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            sock.settimeout(3.0)

            # Send the proxy request to a randomly chosen DNS server

            if protocol == "udp":
                sock.sendto(request, (host, int(port)))
                reply = sock.recv(1024)
                sock.close()

            elif protocol == "tcp":
                sock.connect((host, int(port)))

                # Add length for the TCP request
                length = binascii.unhexlify("%04x" % len(request)) 
                sock.sendall(length+request)

                # Strip length from the response
                reply = sock.recv(1024)
                reply = reply[2:]

                sock.close()

        except Exception, e:
            print "[!] Could not proxy request: %s" % e
        else:
            return reply 

# UDP DNS Handler for incoming requests 
Example 32
Project: mitmfnz   Author: dropnz   File: DNS.py    (license) View Source Project 4 votes vote down vote up
def proxyrequest(self, request, host, port="53", protocol="udp"):
        clientip = {'clientip': self.client_address[0]}

        reply = None
        try:
            if DNSChef().ipv6:

                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

            else:
                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            sock.settimeout(3.0)

            # Send the proxy request to a randomly chosen DNS server

            if protocol == "udp":
                sock.sendto(request, (host, int(port)))
                reply = sock.recv(1024)
                sock.close()

            elif protocol == "tcp":
                sock.connect((host, int(port)))

                # Add length for the TCP request
                length = binascii.unhexlify("%04x" % len(request)) 
                sock.sendall(length+request)

                # Strip length from the response
                reply = sock.recv(1024)
                reply = reply[2:]

                sock.close()

        except Exception as e:
            # log.warning("Could not proxy request: {}".format(e), extra=clientip)
            dnslog.info("Could not proxy request: {}".format(e), extra=clientip)
        else:
            return reply 
Example 33
Project: piSociEty   Author: paranoidninja   File: DNS.py    (license) View Source Project 4 votes vote down vote up
def proxyrequest(self, request, host, port="53", protocol="udp"):
        clientip = {'clientip': self.client_address[0]}

        reply = None
        try:
            if DNSChef().ipv6:

                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

            else:
                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            sock.settimeout(3.0)

            # Send the proxy request to a randomly chosen DNS server

            if protocol == "udp":
                sock.sendto(request, (host, int(port)))
                reply = sock.recv(1024)
                sock.close()

            elif protocol == "tcp":
                sock.connect((host, int(port)))

                # Add length for the TCP request
                length = binascii.unhexlify("%04x" % len(request)) 
                sock.sendall(length+request)

                # Strip length from the response
                reply = sock.recv(1024)
                reply = reply[2:]

                sock.close()

        except Exception as e:
            log.warning("Could not proxy request: {}".format(e), extra=clientip)
            dnslog.info("Could not proxy request: {}".format(e), extra=clientip)
        else:
            return reply 
Example 34
Project: mitmf   Author: ParrotSec   File: DNS.py    (license) View Source Project 4 votes vote down vote up
def proxyrequest(self, request, host, port="53", protocol="udp"):
        clientip = {'clientip': self.client_address[0]}

        reply = None
        try:
            if DNSChef().ipv6:

                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

            else:
                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            sock.settimeout(3.0)

            # Send the proxy request to a randomly chosen DNS server

            if protocol == "udp":
                sock.sendto(request, (host, int(port)))
                reply = sock.recv(1024)
                sock.close()

            elif protocol == "tcp":
                sock.connect((host, int(port)))

                # Add length for the TCP request
                length = binascii.unhexlify("%04x" % len(request)) 
                sock.sendall(length+request)

                # Strip length from the response
                reply = sock.recv(1024)
                reply = reply[2:]

                sock.close()

        except Exception as e:
            log.warning("Could not proxy request: {}".format(e), extra=clientip)
        else:
            return reply 
Example 35
Project: SEF   Author: ahmadnourallah   File: DNS.py    (license) View Source Project 4 votes vote down vote up
def proxyrequest(self, request, host, port="53", protocol="udp"):
        clientip = {'clientip': self.client_address[0]}

        reply = None
        try:
            if DNSChef().ipv6:

                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

            else:
                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            sock.settimeout(3.0)

            # Send the proxy request to a randomly chosen DNS server

            if protocol == "udp":
                sock.sendto(request, (host, int(port)))
                reply = sock.recv(1024)
                sock.close()

            elif protocol == "tcp":
                sock.connect((host, int(port)))

                # Add length for the TCP request
                length = binascii.unhexlify("%04x" % len(request)) 
                sock.sendall(length+request)

                # Strip length from the response
                reply = sock.recv(1024)
                reply = reply[2:]

                sock.close()

        except Exception as e:
            log.warning("Could not proxy request: {}".format(e), extra=clientip)
            dnslog.info("Could not proxy request: {}".format(e), extra=clientip)
        else:
            return reply 
Example 36
Project: SEF   Author: hossamhasanin   File: DNS.py    (license) View Source Project 4 votes vote down vote up
def proxyrequest(self, request, host, port="53", protocol="udp"):
        clientip = {'clientip': self.client_address[0]}

        reply = None
        try:
            if DNSChef().ipv6:

                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

            else:
                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            sock.settimeout(3.0)

            # Send the proxy request to a randomly chosen DNS server

            if protocol == "udp":
                sock.sendto(request, (host, int(port)))
                reply = sock.recv(1024)
                sock.close()

            elif protocol == "tcp":
                sock.connect((host, int(port)))

                # Add length for the TCP request
                length = binascii.unhexlify("%04x" % len(request)) 
                sock.sendall(length+request)

                # Strip length from the response
                reply = sock.recv(1024)
                reply = reply[2:]

                sock.close()

        except Exception as e:
            log.warning("Could not proxy request: {}".format(e), extra=clientip)
            dnslog.info("Could not proxy request: {}".format(e), extra=clientip)
        else:
            return reply 
Example 37
Project: MITMf   Author: wi-fi-analyzer   File: DNS.py    (license) View Source Project 4 votes vote down vote up
def proxyrequest(self, request, host, port="53", protocol="udp"):
        clientip = {'clientip': self.client_address[0]}

        reply = None
        try:
            if DNSChef().ipv6:

                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

            else:
                if protocol == "udp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                elif protocol == "tcp":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            sock.settimeout(3.0)

            # Send the proxy request to a randomly chosen DNS server

            if protocol == "udp":
                sock.sendto(request, (host, int(port)))
                reply = sock.recv(1024)
                sock.close()

            elif protocol == "tcp":
                sock.connect((host, int(port)))

                # Add length for the TCP request
                length = binascii.unhexlify("%04x" % len(request)) 
                sock.sendall(length+request)

                # Strip length from the response
                reply = sock.recv(1024)
                reply = reply[2:]

                sock.close()

        except Exception as e:
            log.warning("Could not proxy request: {}".format(e), extra=clientip)
            dnslog.info("Could not proxy request: {}".format(e), extra=clientip)
        else:
            return reply