我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用socket.sendto()。
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()
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)
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)
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.')
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
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]))
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()
def sendto_ready(packet, socket, future, dest): socket.sendto(packet, dest) asyncio.get_event_loop().remove_writer(socket) future.set_result(None)
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]))
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 ##################################################################################
def send_keepalive_msg(socket, msg, peer): while running: socket.sendto(bytes(msg, 'UTF-8'), peer) time.sleep(timeout)
def send_keepalive_msg(socket, msg, peer): while running: socket.sendto(str.encode(msg), peer) time.sleep(timeout)
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
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))
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)
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()
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)
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
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
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
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