本文整理汇总了Python中socket.sendto函数的典型用法代码示例。如果您正苦于以下问题:Python sendto函数的具体用法?Python sendto怎么用?Python sendto使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sendto函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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")
示例2: handle
def handle(self):
code = self.request[0].strip()
socket = self.request[1]
result = BFParser(code).result
socket.sendto(result, self.client_address)
示例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]))
示例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
示例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)
示例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)
示例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)
示例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)
示例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
示例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()
示例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)
示例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
示例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
示例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)
示例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