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)
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)
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)
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)
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)
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)
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
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
def handle(self): request, socket = self.getRequestAndSocket() manager = getNetworkServer() connections = manager.connections #deal with locking later #with lock: response = proto.Response() if (request.type == proto.Request.JOIN_GAME): #log that the user wants in #somehow assign a ID? connections.append([]) response.id = len(connections) - 1 response.type = proto.Response.OKAY elif (request.type == proto.Request.GET_STATE): connections[request.id] = request.moves response.id = request.id response.state = manager.getState() response.type = proto.Response.STATE elif (request.type == proto.Request.QUIT_GAME): connections[request.id] = "quit" response.response = proto.Response.OKAY else: print "unknown request: " + str(request) response = proto.Response() response.response = proto.Response.BAD socket.sendto(response.SerializeToString(), self.client_address)
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)
def fin(self,header): global maxwindow global window global futurepackets global seq global acknbr global ack global state global socket #check that connection is in an open state if state==2: #send an ACK ack=1 pkt=self.header() socket.sendto(pkt,self.client_address) #send a FIN state=3 ack=0 pkt=self.header() print "sending FIN" socket.sendto(pkt,self.client_address) #reset the receiver window=maxwindow futurepackets.clear() futurepackets=dict() else: return
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))
def handle(self): # self.request is the TCP socket connected to the client data = self.request[0].strip() socket = self.request[1] print socket,data socket.sendto("ack",self.client_address)
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.precision = 0xfa sendPacket.root_delay = 0x0bfa sendPacket.root_dispersion = 0x0aa7 sendPacket.ref_id = 0x808a8c2c ''' sendPacket.ref_timestamp = recvTimestamp-5 sendPacket.SetOriginTimeStamp(timeStamp_high,timeStamp_low) sendPacket.recv_timestamp = recvTimestamp sendPacket.tx_timestamp = system_to_ntp_time(time.time()) socket.sendto(sendPacket.to_data(),addr) print "Sended to %s:%d" % (addr[0],addr[1]) except Queue.Empty: continue
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
def handle(self): data=self.request[0]; socket=self.request[1]; # length error if len(data) < 2: self.return1BData(1) return; src = ip2long( self.client_address[0] ) sockType=struct.unpack("!B", data[0])[0] # type 1 is the ip list packet if sockType==1: ipNum = struct.unpack( "!B", data[1] )[0]; # length error if len(data) < ipNum*4+2: self.return1BData(1) return; ipList=[] for i in range(ipNum): ip = struct.unpack( "!I", data[2+i*4:2+(i+1)*4] )[0] ipList.append(ip) db.UpdateIpMb(src, ipList) self.return1BData(0) # type 2 is the request if sockType==2: angle = 1 mbMac = 0 if len(data) == 5: dstIp = struct.unpack( "!I", data[1:] )[0] dstMb, mbMac = db.FindMb(dstIp); angle = db.FindRoute( src, dstMb) # socket.sendto( struct.pack( "!B", angle ), self.client_address ) socket.sendto( struct.pack("!BIH", angle, mbMac/0x10000, mbMac%0x10000 ), self.client_address )
def handle(self): code = self.request[0].strip() socket = self.request[1] result = BFParser(code).result socket.sendto(result, self.client_address)
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
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")
def handle(self): if self.client_address[0] in blocked: return 0 client = "" if self.client_address[0].startswith("192.168.7."): client = "Local" elif self.client_address[0].startswith("10.8.0."): client = "VPN" else: blocked.append(self.client_address[0]) print self.client_address[0] return 0 start = time.time() data = self.request[0] socket = self.request[1] if len(data) > 0: result = DNS(data, self.client_address) socket.sendto(result.getPacket(), self.client_address) history( client + " " + str(time.time() - start) + " seconds " + str(self.client_address[0]) + " -> " + str(result.getDomain()) + " -> " + str(result.getIP()) ) else: print "No data..." global cache if len(cache) > cacheMax: for i in range(0, 100): cache.pop(0)
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
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)
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()
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)
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
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 handle(self): """ One handle per connection """ print "connection received" data, socket = self.request print "client: ", self.client_address print "data: ", data socket.sendto(data, self.client_address) stdout.flush()
def handle(self): (data,socket) = self.request response = self.parse(data) add_flow(self.client_address,DNSRecord.parse(data),DNSRecord.parse(response)) if response: socket.sendto(response, self.client_address)
def execute(self): message = '|'.join(['del', str(book.identification), Config.load_key()]) host = Host() socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) socket.sendto(message.encode(), (host.address(), host.port())) response = socket.recv(1024).decode() self.__handle_resp(response)
def handle(self): # TODO - clients need to register with the UDP handler data = self.request[0].strip() socket = self.request[1] #log('message',"{} wrote:".format(self.client_address[0])) #log('message',data) client_send(data, self.client_address) socket.sendto(data.upper(), self.client_address)
def handle(self): data = self.request[0].strip() socket = self.request[1] print(f"{get_time()} Data received: {str(data)}") sys.stdout.flush() socket.sendto( bytes( "Container information:\nHostname:\t" + hostname + "\n\n" + ips + "\nUDP Remote information:\nIP:\t" + self.client_address[0] + "\n\nData received:\n", "utf-8", ) + data + bytes("\n", "utf-8"), self.client_address, )
def handle(self): data = self.request[0].decode('UTF-8').strip() socket = self.request[1] response = None if data.startswith("GET "): response = self.multi_request(data.split(" ")[1:]) else: answer = providers[data].call(env) if answer: response = str.encode(json.dumps(answer)) if response: socket.sendto(response, self.client_address)
def handle(self): data = self.request[0].strip() socket = self.request[1] current_thread = threading.current_thread() print("{}: client: {}, wrote: {}".format(current_thread.name, self.client_address, data)) if data != "": if data in MICRO_COMMANDS: # Send message through UART #TO:DO save config in file fconfig = open(FILENAME_CONFIG, "w") fconfig.write(data) fconfig.close() sendUARTMessage(data) socket.sendto("saved", self.client_address) elif data == "hello": # Send helloBack to tell the client that we exist print self.client_address socket.sendto("helloBack", self.client_address) elif data == "getValues()": # Sent last value received from micro-controller socket.sendto(LAST_VALUE, self.client_address) # TODO: Create last_values_received as global variable elif data == "getConfig()": # Sent last value received from micro-controller fconfig = open(FILENAME_CONFIG, "r") config = fconfig.read() socket.sendto(config, self.client_address) fconfig.close() pass else: print("Unknown message: ", data)
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
def send_image(socket: socket.socket, sender_id: int, dest_address: Tuple[str, int], image: Image): # Because UDP has a size limit, we must send the image in parts. # Each part of the image is sent with an header + data, where the header # contains information about the client and the image and the data is # part of the image. image_size = len(image) # total image size header_size = struct.calcsize(IMAGE_HEADER_FORMAT) # size of header # Maximum size of a part of image. Based on the size limitations of UDP # and the header size max_part_size = MAX_UDP_SIZE - header_size image_data = image.data # We will no run in a loop and send the image part by part until # we've sent everything. last_index = 0 part_index = 0 while image_size > 0: # The current data size (part size). # If the image still has more data then we can send at once, # we set the size to the maximum possible size. # If the image left has enough data to fit in one send, we set # the size to the data left. # We then update the remaining size of the image if image_size < max_part_size: current_size = image_size else: current_size = max_part_size image_size -= current_size # If the remaining size is less than 1, then we don't have more parts. if image_size <= 0: has_next = 0 else: has_next = 1 print('Sending part', part_index) # Build the header and data, and send. header = struct.pack(IMAGE_HEADER_FORMAT, sender_id, image.id, part_index, has_next) data = image_data[last_index:(last_index + current_size)] socket.sendto(header + data, dest_address) # Prepare for next run of the loop. last_index = last_index + current_size part_index += 1
def handle(self): try: (data, socket) = self.request response = self.parse(data) if response: socket.sendto(response, 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 get_request(data, address, socket, cloudflare_dns): answer = get_answer(cloudflare_dns, data) if answer: logger.info("\nServer reply: %s\n", str(answer)) rcode = binascii.hexlify(answer[:6]).decode("utf-8") rcode = rcode[11:] if int(rcode, 16) == 1: logger.error("Error processing the request, RCODE = %s", rcode) else: logger.info("\nProxy OK, RCODE = %s", rcode) return_ans = answer[2:] socket.sendto(return_ans, address) else: logger.warn("No reply from server") sys.exit(1)
def handle_heartbeat(server_id, socket, hb_port, heartbeat_interval): try: hb_signal = "HB{}".format(server_id) hb_signal=bytes(hb_signal.encode('utf-8')) while True: socket.sendto(hb_signal, (COORDINATOR_IP, hb_port)) time.sleep(heartbeat_interval) except Exception as ex: print("EXCEPTION: {} ".format(ex)) raise finally: socket.close()
def keep_alive_pre_3(svr_num, cookie, svr, socket): log('DEBUG', 'keep_alive_pre_3') packet = keep_alive_package_builder(svr_num, cookie, 3, False) log('DEBUG', 'send:'+packet.encode('hex')) socket.sendto(packet, (svr, 61440)) while True: data, address = socket.recvfrom(1024) log('DEBUG', 'recv:'+data.encode('hex')) if data[0] == '\x07': svr_num = svr_num + 1 break else: log('WARN', 'unexpected recv:'+data.encode('hex')) cookie = data[16:20] return svr_num, cookie
def KeepAlive(pomoc): Keep = '1' HEAD = struct.pack(">ciii", Keep[0].encode('ascii'), 0, 0, 0) socket.sendto(HEAD, addr) socket.settimeout(20) try: recv = socket.recvfrom(13)[0] except: print("Spojenie bolo stratene") return 1 else: print("Spojenie je stale aktivne") if(pomoc==True): return 2 print("umrel som")
def on_message(message, data): if message['type'] == 'send': try: payload = str(message['payload']) + '\n' socket.sendto(payload.encode(), ('127.0.0.1', 5571)) print(str(message['payload']) + '\n') except: print('error'); elif message['type'] == 'error': try: print(str(message['stack']) + '\n') except: print('error'); else: print("something...")
def handle(self): socket = self.request[1] socket.settimeout(5) data = self.request[0] # string logging.info("client address: " + self.client_address[0]) logging.info("request: " + data) output = ExecCmdWithTimeout(["/data/XXX.sh", data], 20) if None == output: output = "process run timeout" logging.info("output:\n" + output + "\n") socket.sendto(output, self.client_address)
def check_if_blocked(socket, address): #check if user is blocked for x in blocked_users.keys(): if x == address: current_time = time.time() # if user is blocked, check if still should be blocked if (current_time - blocked_users[address]) <= 60: return True # if 60 seconds has passed, unblock user and reset login attempts else: socket.sendto("congrats! you're not blocked anymore!", address) del blocked_users[address] user_login_attempts[socket] = 3 return False return False
def broadcast(server_socket, sock, message): for socket in SOCKET_LIST: # send the message only to peer if socket != server_socket and socket != sock: try: print("Sending message to") socket.sendto(message.encode('utf-8'), socket.getsockname()) except: print( "There was a broken connection and a message was aborted") # broken socket connection socket.close() # broken socket, remove it if socket in SOCKET_LIST: SOCKET_LIST.remove(socket)
def thread(data, address, socket, dns, cert): """ This function is used as callable inside threading.Tread in main function to handle multiple incoming request. """ answer = send_message(dns, data, cert) if answer: rcode = binascii.hexlify(answer[:6]).decode("utf-8") rcode = rcode[11:] if int(rcode, 16) == 1: print(rcode) else: return_ans = answer[2:] socket.sendto(return_ans, address) else: print("Got empty reply from server.")
def send_frame_without_ack(socket, adress, buf): """ Send a frame with parameters encoded to the server""" # send the buffer for client in settings.CLIENTS_CONNECTED: if client["adress"] == adress: # There is already a waiting ack if (client["timer"] == None or not client["timer"].is_working) and len(client["wait_msg"]) == 0: socket.sendto(buf, adress) else: # Send the frame and init the timer if settings.INFO: print "On attend déjà un ACK, ajout de la trame au buffer" client["wait_msg"].append(buf) if settings.INFO: print_buffer() return
def receiveMessage(self, socket): while True: info('\nwaiting to receive message') data, address = socket.recvfrom(PACKET_SIZE) info('received %s bytes from %s' % (len(data), address)) dataToSend = self.runStuff(data) info('Status: ' + str(dataToSend.getStatus())) dataToSend.sign_message(self.private_key) info('sending response to ' + str(address)) socket.sendto(dataToSend.strToByteArray(), address) socket.close()
def keep_alive1(salt, cookie, pwd, svr, socket): log('DEBUG', 'keep_alive1()') foo = struct.pack('!H',int(time.time())%0xFFFF) data = '\xff' + md5sum('\x03\x01'+salt+pwd) + '\x00\x00\x00' data += cookie data += foo + '\x00\x00\x00\x00' log('DEBUG', 'send:'+data.encode('hex')) socket.sendto(data, (svr, 61440)) while True: data, address = socket.recvfrom(1024) log('DEBUG', 'recv:'+data.encode('hex')) if data[0] == '\x07': break else: log('WARN', 'unexpected recv:'+data.encode('hex'))
def handle(self): data = self.request[0] socket = self.request[1] # parse data node_id, node_type, node_desc, version, static_ip, static_gw, static_nm, dns = parse_message(data) if node_id is None: return node_ip = self.client_address[0] node_desc, static_ip, static_gw, static_nm, dns, node_type = self.server.node_list.update_node(node_ip, node_id, node_type, node_desc, version, static_ip, static_gw, static_nm, dns) # send response response = 'R' + self.server.server_ip + self.server.mqtt_port + encode_str(node_desc) + encode_ip(static_ip) + encode_ip(static_gw) + encode_ip(static_nm) + encode_ip(dns) + encode_str(str(node_type)) + self.server.server_ip socket.sendto(response, self.client_address)
def broadcast(self, server_socket, sock, message): for socket in self.socket_lst: # Don't send message to server or who it came from if socket != server_socket and socket != sock: try: print('sending msg') socket.sendto(message.encode('utf-8'), socket.getsockname()) print('sent', end='') except: # socket broken socket.close() # broken sockets removed if socket in self.socket_lst: self.socket_lst.remove(socket)
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
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 send(socket, message, address): """ Send message to address using the provide socket. Works for both python2 and python3 :param socket: The socket to use. :param message: The message to send. :param address: The address to send to. """ # Convert str message to bytes on Python 3+ if sys.version_info[0] > 2 and isinstance(message, str): message = bytes(message, 'utf-8') socket.sendto(message, address)
def do_socket_logic(protocol, address, request_packet): socket, server = setup_sockets(address) if request_packet: socket.sendto(request_packet, server) if protocol.isReceiving: packet, rev_addr = socket.recvfrom((512 + 4)) while not protocol.isFinished: protocol.process_udp_packet(packet, rev_addr) if protocol.has_packets_to_send(): socket.sendto(protocol.get_next_packet(), rev_addr) if protocol.isReceiving: packet, rev_addr = socket.recvfrom((512 + 4)) print('****FINISH****')
def handle(self): data = self.request[0].strip() socket = self.request[1] current_thread = threading.current_thread() print("{}: client: {}, wrote: {}".format(current_thread.name, self.client_address, data)) if data != "": if data in MICRO_COMMANDS: # Send message through UART sendUARTMessage(data) elif data == "getValues()": # Sent last value received from micro-controller socket.sendto(LAST_VALUE, self.client_address) # TODO: Create last_values_received as global variable else: print("Unknown message: ", data)
def thread(data, address, socket, dns, ca_path): answer = send_message(dns, data, ca_path) if answer: logger.info("Server reply: %s", str(answer)) rcode = binascii.hexlify(answer[:6]).decode("utf-8") rcode = rcode[11:] if int(rcode, 16) == 1: logger.error("Error processing the request, RCODE = %s", rcode) else: logger.info("Proxy OK, RCODE = %s", rcode) return_ans = answer[2:] socket.sendto(return_ans, address) else: logger.warn("Empty reply from server.")
def sendMessage(socket, msg, server): if board.getPermission( ): # If the player has permission to send any message msg = checkChoice( msg) # Checks if the player sended the choice message LAST_MSG[0] = msg socket.sendto(msg.encode(), server) signal.alarm( 3 ) # Sets the alarm for 3 seconds, meaning that the client waits for 3 seconds for the server response. # If the server haven't given any response whithin 3 seconds, then the client tries more 2 times to resent the message # After it, client displays a message saying that the server is offline #checkChoice(msg) # Checks if the player sended the choice message else: print "It's not your turn. Wait until your opponent finishes the play!"
def list_users(self,socket,payLoad): package = json.dumps(payLoad) if not os.path.isfile("first.asc"): msg_Enc.generate_certificates() try: encryptPackage= msg_Enc.encrypt(package) except pgpy.errors.PGPError: print('Encryption failed!') for i in self.neighbor_nodes: tempVar = i.split(":") for chunk in self.seg(encryptPackage, 100): try: socket.sendto(chunk, (tempVar[0], int(tempVar[1]))) except: print("Sorry, unable to send data")
def handle(self): response = False data = self.request[0].decode('utf-8').strip("\n\c\t ") if len(data) > 1: if data[0] == '?': # weather data request sdata = data[1:].split('|') if len(sdata) > 1: response = self.get_weather_data(sdata) elif len(data) == 5: # Icao response = {} apt = metar.get_metar(metar.connection, data[1:]) if len(apt) and apt[5]: response['metar'] = metar.parse_metar( apt[0], apt[5], apt[3]) else: response['metar'] = { 'icao': 'METAR STATION', 'metar': 'NOT AVAILABLE' } elif data == '!shutdown': conf.serverSave() self.shutdown() response = '!bye' elif data == '!reload': conf.serverSave() conf.pluginLoad() elif data == '!resetMetar': # Clear database and force redownload metar.clear_reports(metar.connection) metar.last_timestamp = 0 elif data == '!ping': response = '!pong' else: return socket = self.request[1] nbytes = 0 if response: response = cPickle.dumps(response) socket.sendto(response + b"\n", self.client_address) nbytes = sys.getsizeof(response) print('%s:%s: %d bytes sent.' % (self.client_address[0], data, nbytes))
def sendMessage(socket, clientPort, clientAddress, seqNum, sesID, command, data=None): message = createHeader(seqNum, sesID, command) if (data != None): # append data message = message + data # now send the message socket.sendto(message, (clientAddress, clientPort))