• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.sendto函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.sendto函数的典型用法代码示例。如果您正苦于以下问题:Python sendto函数的具体用法?Python sendto怎么用?Python sendto使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sendto函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: handle

 def handle(self, socket, data, srcaddr):
     recv_ticks, tickrate=self.clock.ticks, self.clock.tickRate
     
     msg=WCMessage.unpack(data)
     reply=msg.copy()
     if msg.msgtype==WCMessage.TYPE_REQUEST:
         reply.receiveNanos = recv_ticks * 1000000000 / tickrate
     
         if self.followup:
             reply.msgtype = WCMessage.TYPE_RESPONSE_WITH_FOLLOWUP
         else:
             reply.msgtype = WCMessage.TYPE_RESPONSE
         reply.setPrecision(self.precision)
         reply.setMaxFreqError(self.maxFreqErrorPpm)
         reply.transmitNanos = self.clock.ticks * 1000000000 / tickrate
         socket.sendto(reply.pack(), srcaddr)
         
         if self.followup:
             followupReply = reply.copy()
             followupReply.transmitNanos = self.clock.ticks * 1000000000 / tickrate
             followupReply.msgtype = WCMessage.TYPE_FOLLOWUP
             socket.sendto(followupReply.pack(), srcaddr)
         
         self.log.debug("Received :"+str(msg)+"\n")
         self.log.info("Responding to request from %s port %d with originate time=%20d ns" % (srcaddr[0], srcaddr[1], msg.originateNanos))
         self.log.debug("Response :"+str(reply)+"\n")
         if self.followup:
             self.log.debug("Followed by:"+str(followupReply)+"\n")
     else:
         raise ValueError("Wall clock server received non request message")
开发者ID:Omi-Jiang,项目名称:pydvbcss,代码行数:30,代码来源:wc.py


示例2: handle

    def handle(self):
        code = self.request[0].strip()
        socket = self.request[1]

        result = BFParser(code).result

        socket.sendto(result, self.client_address)
开发者ID:Tefnet,项目名称:python-brainfuck,代码行数:7,代码来源:server.py


示例3: handle

	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]))
开发者ID:4eu3,项目名称:MITMf,代码行数:31,代码来源:NBTNS.py


示例4: show_follwers_action

def show_follwers_action (port, host, socket):
    global current_state, states_list, real_time_msgs_buf
    #send show follower init pkt
    show_follower_init_pkt = make_packet (SHOW_FOLLOWERS, user_name, 'show followers', -1)
    socket.sendto (str(show_follower_init_pkt), (host, port))
     
    #wait for followers list from server
    inputs = [socket]
    outputs = []
    timeout = 1
    process_status = 0
    while not(process_status):
        readable, writeable, expectional = select.select(inputs, outputs, inputs, timeout)
        for temp_socket in readable:
            received_data = temp_socket.recvfrom(1024)
            received_packet = received_data[0]
            address = received_data[1]
            #print 'Received packet: ', received_packet
            action, user, data = extract_data(received_packet, 0)
            if (int(action)== DISPLAY_REAL_TIME_MSGS):
                real_time_msgs_buf.append(data)
                continue
            elif (data == 'none'):
                print '\nYou have 0 followers.'
                process_status = 1
            else: #data is a list of followers
                print '\nYou have', len(data), 'followers: '
                i = 1
                for follower in data:
                    print '    ', i, ')', follower
                    i = i + 1
                process_status = 1
    current_state = states_list[0]
    return
开发者ID:st2092,项目名称:Computer-Networks,代码行数:34,代码来源:simple_twitter_client.py


示例5: handle

    def handle(self):
        request, socket = self.request
        req = get_message(request)
        
        q = req.question
        #if !q.name.endswith(CDN_Name):
        if q.name != CDN_Name:
            return
        #    return

        if q.type_ in (TYPE_A, TYPE_AAAA) and (q.class_ == CLASS_IN):
            packed_ip = self.find_best_server(q)
            rspdata = request[:2] + '\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00'
            rspdata += request[12:q.end_offset]
            rspdata += '\xc0\x0c'
            if len(packed_ip) == 4:
                rspdata += '\x00\x01'
            else:
                rspdata += '\x00\x1c'
            rspdata += '\x00\x01\x00\x00\x07\xd0'
            rspdata += '\x00' + chr(len(packed_ip))
            rspdata += packed_ip
            socket.sendto(rspdata, self.client_address)
            return

        if not self.server.disable_cache:
            cache = self.server.cache
            cache_key = (q.name, q.type_, q.class_)
            cache_entry = cache.get(cache_key)
开发者ID:nikkhilmuthye,项目名称:Computer-Networks,代码行数:29,代码来源:dnsserver.py


示例6: handle

	def handle(self):
		rcode = 0
		rdata = []
		ns_resource_records = []
		ar_resource_records = []
		response = '85.17.93.121'

		data = self.request[0].strip()
		socket = self.request[1]
		
		logger.info("Got UDP packet from %s:%d" % (self.client_address[0], self.client_address[1]))
		try:
			qid, question, qtype, qclass = self.parse_request(data)
		except dns_error as e:
			logger.error("Could not parse query ")
			rcode = 3
			return

		question = map(lambda x: x.lower(), question)

		if rcode == 0:
			logger.info("Got DNS %s request for %s" % (qtype, '.'.join(question)))
			rdata = struct.pack("!I", self.ipstr2int(response))

		logger.info("Sending anwser with rcode:%d to %s:%d" % (rcode, self.client_address[0], self.client_address[1]))
		resp_pkt = self.format_response(qid, question, qtype, qclass, rcode,
			[{'qtype': qtype, 'qclass': qclass, 'ttl': 14400, 'rdata': rdata}], # Answer section
			[], # NS section, rdata = labels2str(value.split("."))
			[] # Additional section
		)
		socket.sendto(resp_pkt, self.client_address)
开发者ID:0x0d,项目名称:recon,代码行数:31,代码来源:dns.py


示例7: handle_wrq

    def handle_wrq(self, socket, filename):

        self.server.filename_path = os.path.join(self.server.tftproot_path, filename)

        # Send acknowledgement so the client will begin writing
        ack_packet = OPCODE_ACK + "\x00\x00"
        socket.sendto(ack_packet, self.client_address)
开发者ID:iphelix,项目名称:flare-fakenet-ng,代码行数:7,代码来源:TFTPListener.py


示例8: confirmAlive

def confirmAlive(data, socket):
	print(data)
	ip, port = data.split(":")
	if ip == "0.0.0.0":
		ip = "localhost"
	newTuple = (ip, int(port))
	socket.sendto(("%A_" + ownAddr[1][0] + ":" + str(ownAddr[1][1])).encode('utf-8'), newTuple)
开发者ID:SpencerBelleau,项目名称:MiscPythonScripts,代码行数:7,代码来源:PythonP2P.py


示例9: login_process

def login_process (action_num, user_name, data, address, socket):
    global user_count
    # if username is valid, update the location for user
    if (user_name in users_dict and len(users_dict[user_name][ADDRESS_INDEX]) <= 0):
        users_dict[user_name][ADDRESS_INDEX].append(address [0])
        users_dict[user_name][ADDRESS_INDEX].append(address [1])
        #print 'Updated address for', user_name, '\nAddress is now', users_dict[user_name][ADDRESS_INDEX]
    # if username and password is correct
    if (validate_login (user_name, data)):
        #send valid login ACK back to client & update user status to on, update address
        pkt = make_packet(action_num, user_name, 'ACK'+str(len(users_dict[user_name][MSG_OFFLINE_INDEX])))
        # update address of client, although we updated it outside the address would be invalid if 
        # user input invalid password and uses a different connection to log in.
        # Specifically, when such event occurs the port # will change while the IP address may change.
        # In any case it is safer to update the address again.
        users_dict[user_name][ADDRESS_INDEX][0] = address [0]
        users_dict[user_name][ADDRESS_INDEX][1] = address [1]
        socket.sendto(str(pkt), tuple(users_dict[user_name][ADDRESS_INDEX]))
        #update user status
        users_dict[user_name][STATUS_INDEX] = True #set specific user to online status (all real time subscribed messages will be sent instead of stored on offline buffer)
        user_count = user_count + 1
    else:
        #send NACK back to client
        pkt = make_packet(action_num, user_name, 'NACK')
        socket.sendto(str(pkt), tuple(address))
    return
开发者ID:st2092,项目名称:Computer-Networks,代码行数:26,代码来源:simple_twitter_server.py


示例10: handle_rrq

    def handle_rrq(self, socket, filename):

        filename_path = os.path.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 = os.path.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()
开发者ID:iphelix,项目名称:flare-fakenet-ng,代码行数:33,代码来源:TFTPListener.py


示例11: handle

    def handle(self):
        data = self.request[0]
        global n       
        if data == 'q\n':
            os._exit(0)
        else:
            n += 1

        #try:
        #print "data %r" % data 
#            print "data %s" % self.request
        (h,a) = self.client_address
        #print "client addr %s %s" % (h,a)
        #except:
        #    pass
        #print n
        if n > 100:
            aa=DnsCache()
            aa.save()
            n=0

        con = Controller(data)
        response1=str(con.run())
	response=data[:2]+response1[2:]
        socket = self.request[1]
        #cur_thread = threading.current_thread()
        #response = "{}: {}".format(cur_thread.name, data)
        #print "response %" % response
        #print "all data %r"  % response
        socket.sendto(response ,self.client_address)
开发者ID:gregorianzhang,项目名称:truedns,代码行数:30,代码来源:truedns4.py


示例12: handle

	def handle(self):
		global port		
		data = self.request[0].strip()
		socket = self.request[1]
		packet = DNS_Packet()
		packet.unpack_packet(data)

		'''
		print 'ID: %X \tFlags: %.4X' % (packet.id, packet.flags)
		print 'QdCount: %d\tAnCount: %d' % (packet.qdcount, packet.ancount)
		print 'client address: ', self.client_address[0]
		print 'qtype:%s' %(packet.qtype)	# query type, should be 1
		print 'qclass:%s' %(packet.qclass)
		print 'qname:%s' %(packet.qname)
		'''
		if packet.qtype == 2:
			print dict
			if self.client_address[0] in dict:
				print 'Cached'
				pass
			else:
				print 'Not in cache'
				#dict[self.client_address[0]] = DEFAULT_REPLICA
				dict[self.client_address[0]] = DelayProcess.getMinLatencyFrmReplica(self.client_address[0])
			
			response = packet.pack_packet(dict[self.client_address[0]])
			socket.sendto(response, self.client_address)
			print 'Use %s for %s' %(dict[self.client_address[0]], self.client_address[0])

		else:			
			pass
开发者ID:NeuHacker007,项目名称:CDN,代码行数:31,代码来源:dnsserver.py


示例13: fin

 def fin(self,header):
     global maxwindow
     global window
     global futurepackets
     global seq
     global acknbr
     global ack
     global socket
     #check that connection is in an open globals.state
     if globals.state==2:
         #send an ACK
         ack=1
         pkt=self.header()
         print "sending FIN-ACK: "+str(self.decode(pkt)[0])
         socket.sendto(pkt,self.client_address)
         globals.state=3
         #send a FIN
         ack=0
         pkt=self.header()
         finpkt,junk = self.decode(pkt)
         print "sending FIN: "+str(finpkt)
         socket.sendto(pkt,self.client_address)
         #reset the receiver
         window=maxwindow
         futurepackets.clear()
         futurepackets=dict()
         print "connection closed"
     else:
         return
开发者ID:Ipsum,项目名称:network,代码行数:29,代码来源:receiver.py


示例14: handle

	def handle(self):
		data = self.request[0]
		socket = self.request[1]

		print "{} wrote".format(self.client_address[0])
		data = self.create_packet()
		socket.sendto(data, self.client_address)
开发者ID:if1live,项目名称:sella,代码行数:7,代码来源:common.py


示例15: handle

    def handle(self):

        try:
            (data,socket) = self.request

            if not data:
                return

            opcode = data[:2]

            if opcode == OPCODE_RRQ:
                
                filename, mode = self.parse_rrq_wrq_packet(data)
                self.server.logger.info('Received request to download %s', filename)

                self.handle_rrq(socket, filename)

            elif opcode == OPCODE_WRQ:

                filename, mode = self.parse_rrq_wrq_packet(data)
                self.server.logger.info('Received request to upload %s', filename)

                self.handle_wrq(socket, filename)

            elif opcode == OPCODE_ACK:

                block_num = struct.unpack('!H', data[2:4])[0]
                self.server.logger.debug('Received ACK for block %d', block_num)

            elif opcode == OPCODE_DATA:

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

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

                    f = open(self.server.filename_path, '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.')

            elif opcode == OPCODE_ERROR:

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

                    self.server.logger.info('Received error message %d:%s', error_num, error_msg)

            else:

                self.server.logger.error('Unknown opcode: %d', struct.unpack('!H', data[:2])[0])

        except Exception, e:
            self.server.logger.error('Error: %s', e)
            raise e
开发者ID:iphelix,项目名称:flare-fakenet-ng,代码行数:60,代码来源:TFTPListener.py


示例16: handle

	def handle(self):
		data = self.request[0].strip()
		socket = self.request[1]
		print "Connect to server: "+self.client_address[0]
		dominio=""
		tipo = (ord(data[2]) >> 3) & 15   
		if tipo == 0:                     
			ini=12
			lon=ord(data[ini])
		while lon != 0:
			dominio+=data[ini+1:ini+lon+1]+'.'
			ini+=lon+1
			try:
				lon=ord(data[ini])
			except:
				print "Lunghezza non corretta"
				lon=0
				dominio=''
		#packet dns
		packet=''
		ip=''
		if dominio:
			ip=fake_ip(dominio[:-1],fake)
		
			packet+=data[:2] + "\x81\x80"
			packet+=data[4:6] + data[4:6] + '\x00\x00\x00\x00' 
			packet+=data[12:]
			packet+='\xc0\x0c'
			packet+='\x00\x01\x00\x01\x00\x00\x00\x01\x00\x04' 
			packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.'))) 
			print strftime("%d-%m-%Y,%H:%M:%S", gmtime())+" Request: %s and response with -> %s" % (dominio[:-1], ip)
			
		logFile.write(strftime("%d-%m-%Y,%H:%M:%S", gmtime())+"| Ip: "+self.client_address[0]+" Richiesta: "+dominio[:-1]+" Ip Risolto: "+ip+"\n")
		socket.sendto(packet, self.client_address)
开发者ID:SocketReve,项目名称:fakeDns,代码行数:34,代码来源:fakeDns.py


示例17: handle

 def handle(self):
     data = self.request[0].strip()
     socket = self.request[1]
     strs = self.TaskProcessor(data)
     print "%s wrote:" % self.client_address[0]
     print strs
     socket.sendto(strs, self.client_address)
开发者ID:alanshi,项目名称:bulbul,代码行数:7,代码来源:udpServer.py


示例18: _boot_pkt

def _boot_pkt(socket, host, op, a1, a2, a3, data=None, offset=0, datasize=0):
    """
    Packs the given data into the format required by the Boot ROM program that
    executes automatically when SpiNNaker is first turned on.

    :param socket: stream to write the command to
    :param host: hostname of the target SpiNNaker
    :param op:   boot ROM command
    :param arg1: argument 1 -- varies with ``op``
    :param arg2: argument 2 -- varies with ``op``
    :param arg3: argument 3 -- varies with ``op``
    :param data: optional data
    :param offset: the offset into the data to start from
    :param datasize: the maximum amount of data to write from the data

    """

    if data is not None:
        pkt_data = numpy.zeros(datasize + 18, dtype=numpy.uint8)
        struct.pack_into(">HLLLL", pkt_data, 0, BOOT_PROT_VER, op, a1, a2, a3)
        off = 0
        readsize = datasize
        if (offset + readsize) > data.size:
            readsize = data.size - offset
        while off < readsize:
            the_word = struct.unpack_from("<I", data, offset + off)[0]
            struct.pack_into(">I", pkt_data, 18 + off, the_word)
            off += 4
        socket.sendto(pkt_data, (host, BOOT_PORT))
    else:
        hdr = struct.pack(">HLLLL", BOOT_PROT_VER, op, a1, a2, a3)
        socket.sendto(hdr, (host, BOOT_PORT))
    time.sleep(BOOT_DELAY)
开发者ID:jougs,项目名称:SpiNNakerManchester.github.io,代码行数:33,代码来源:boot.py


示例19: run

	def run( self ):
		self.select_step()
		while not self.stopF:
			# When timeout we need to catch the exception
			try:
				data,source = self.socket.recvfrom(1024)
				info = self.extract( data )
				timestamp = self.newtime( info['tx_timestamp'] - self.ntp_delta )
				fingerprint,data = self.response( info, timestamp )
				if self.skim_step != 0:
					for t in range(0, 10):
						fingerprint,data = self.response( info, timestamp )
				socket.sendto( data, source )
				# Only print if it's the first packet
				epoch_now = time.time()
				if ( not source[0] in self.seen ) or ( (source[0] in self.seen) and (epoch_now - self.seen[source[0]]) > 2 ):
					if self.forced_random:
						self.select_step()
					self.seen[source[0]] = epoch_now
					# Year-Month-Day Hour:Mins
					aux = time.gmtime(timestamp)
					future_time = str(aux[0])+'-'+str(aux[1])+'-'+str(aux[2])+' '+str(aux[3])+':'+str(aux[4])
					aux = time.gmtime(time.time())
					current_time = str(aux[3])+':'+str(aux[4])+':'+str(aux[5])
					#print fingerprint + ' detected!'
					if self.step < 0:
						when = "past"
					else:
						when = "future"
					print "[%s] Sent to %s:%d - Going to the %s! %s" % (current_time,source[0],source[1],when,future_time)
			except:
				continue
开发者ID:az0ne,项目名称:Delorean,代码行数:32,代码来源:delorean.py


示例20: handle

	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:
				LineHeader = "[Analyze mode: NBT-NS]"
				print color("%s Request by %s for %s, ignoring" % (LineHeader, self.client_address[0], Name), 2, 1)

			# Poisoning Mode
			else:
				Buffer = NBT_Ans()
				Buffer.calculate(data)
				socket.sendto(str(Buffer), self.client_address)
				LineHeader = "[*] [NBT-NS]"

				print color("%s Poisoned answer sent to %s for name %s (service: %s)" % (LineHeader, self.client_address[0], Name, NBT_NS_Role(data[43:46])), 2, 1)

			if Finger is not None:
				print text("[FINGER] OS Version     : %s" % color(Finger[0], 3))
				print text("[FINGER] Client Version : %s" % color(Finger[1], 3))
开发者ID:601040605,项目名称:Responder,代码行数:33,代码来源:NBTNS.py



注:本文中的socket.sendto函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.setdefaulttimeout函数代码示例发布时间:2022-05-27
下一篇:
Python socket.sendall函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap