def request_data(): """ Push data to correlation graph """ socket.send_string("Request_%s" % self.plotName.replace(' ', '_')) nowStr = time.strftime("%b %d %Y %H:%M:%S", time.localtime()) print( "correlation plot %s requested data at %s, plot %g seconds " % (self.plotName, nowStr, time.time() - self.plotStartTime)) print '*** waiting' data_dict = socket.recv_pyobj() print '*** received' pdSeriesDict = {} # FIX ME: why this? # Get time from data_dict print("total time data: ", data_dict['event_time'][0], data_dict['event_time'][-1]) timeData = data_dict['event_time'][-self.number_of_events:] modTimeData = timeData[:, 0] + (timeData[:, 1] * 1e-6).astype(int) * 1e-3 print("got data starting at: ", modTimeData[0], len(modTimeData)) for key in self.data.keys(): pdSeriesDict[key] = pd.Series( data_dict[key][-self.number_of_events:], index=modTimeData) full_frame = pd.DataFrame(pdSeriesDict) self.streamData.event(df=full_frame)
def send_alive_messages(node_id, address, ports): # context = zmq.Context() global context socket = context.socket(zmq.PUB) port = "" while (port == ""): for sample_port in ports: try: socket.connect("tcp://%s:%s" % (address, sample_port)) print("Sending ALIVE messages to %s:%s" % (address, sample_port)) port = sample_port break except zmq.ZMQError: print( "Could not connect to %s:%s.. Trying another port-address.." % (address, sample_port)) if port == "": print("Error: there are no free ports. Exiting..") os.killpg( os.getpgid(os.getpid()), signal.SIGTERM) # This is done to kill the parent process as well. sys.exit() while True: message_str = str("%d %s" % (node_id, "ALIVE")) print("Node %d: Sending %s to %s:%s" % (node_id, message_str, address, port)) socket.send_string(message_str) time.sleep(1)
def recieve_replica(offset, replica_port): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % replica_port) print("finished binding to replicas") while True: #json = socket.recv_json() #parsed_json = json.loads() #socket.send_string("AY 7aga") #received the json and ACK is sent message = socket.recv() #file and json is received print("I received") message = pickle.loads(message) z = message["file"] p = zlib.decompress(z) sent_file = pickle.loads(p) #p = zlib.decompress(message) #data = pickle.loads(p) directory = "./" + message["username"] if not os.path.exists(directory): os.makedirs(directory) with open(directory + "/" + offset + message["filename"], 'wb') as f: f.write(sent_file) socket.send_string("finished writting file, success")
def recieve_replica(replica_port): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % replica_port) print("finished binding to receive replicas") while True: message = socket.recv() #file and json is received print("received replication request") message = pickle.loads(message) parsed_json = message z = parsed_json["file"] p = zlib.decompress(z) sent_file = pickle.loads(p) extension_index = len(parsed_json["filename"]) if "." in parsed_json["filename"]: extension_index = parsed_json["filename"].rfind(".") directory = "./" + parsed_json["username"] + "/" + str( parsed_json["filename"])[:extension_index] if not os.path.exists(directory): os.makedirs(directory) with open(directory + "/" + parsed_json["filename"], 'wb') as f: f.write(sent_file) ####will slice here########done and tested####### number_of_chunks = slice_file(directory, parsed_json["filename"], 64 * 1024) socket.send_string("finished writting file, success")
def send(self, socket, event_history): """ Sends the encapsulated response data via the specified socket Parameters ---------- socket : zmq.Socket event_history : EventHistory The RPC event history that should be updated as a result of this operation """ assert self.num_outputs > 0 output_header, header_length_bytes = self._create_output_header() if sys.version_info < (3, 0): socket.send("", flags=zmq.SNDMORE) else: socket.send_string("", flags=zmq.SNDMORE) socket.send( struct.pack("<I", MESSAGE_TYPE_CONTAINER_CONTENT), flags=zmq.SNDMORE) socket.send(self.msg_id, flags=zmq.SNDMORE) socket.send(struct.pack("<Q", header_length_bytes), flags=zmq.SNDMORE) socket.send(output_header, flags=zmq.SNDMORE) for idx in range(self.num_outputs): if idx == self.num_outputs - 1: # Don't use the `SNDMORE` flag if # this is the last output being sent socket.send(self.outputs[idx]) else: socket.send(self.outputs[idx], flags=zmq.SNDMORE) event_history.insert(EVENT_HISTORY_SENT_CONTAINER_CONTENT)
def getblockbyheight(self, request=None, response=None): """ Get block by height """ if request is None and response is None: # If no data is being passed on by command handler pass if request is not None: # Processing requests UDPHandler.sendmessage( json.dumps({ "command": "getblockbyheight", "body": request["height"] }), request["ip_addr"]) if response is not None: # Processing reaponse if "command" in response.keys(): blk = self.redis_client.lindex( 'chain', response["body"]).decode("utf-8") UDPHandler.sendmessage( json.dumps({ "prev_command": "getblockbyheight", "body": blk }), response["ip_addr"]) elif "prev_command" in response.keys(): context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) socket.send_string(json.dumps(response)) msg = socket.recv() print(msg)
def get_disk_space(self, request=None, response=None): """ Ask for disk space """ if request is None and response is None: # If no data is being passed on by command handler pass if request is not None: # Processing requests UDPHandler.broadcastmessage( json.dumps({ "command": "getspace", "body": {} })) if response is not None: # Processing reaponse if "command" in response.keys(): curr_dir = os.getcwd() print(curr_dir) stats = shutil.disk_usage(curr_dir) print("Your free space in mbs: ") print(stats.free * 0.00000095367432) UDPHandler.sendmessage( json.dumps({ "prev_command": "get_space", "data": stats.free }), response["ip_addr"]) elif "prev_command" in response.keys(): context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:%s" % settings.STORAGE_ZMQ_PORT) socket.send_string(json.dumps(response)) msg = socket.recv() print(msg)
def getchainlength(self, request=None, response=None): """ Get length of Blockchain """ if request is None and response is None: # If no data is being passed on by command handler pass if request is not None: # Processing requests UDPHandler.sendmessage( json.dumps({ "command": "getchainlength", "body": "" }), request["ip_addr"]) if response is not None: # Processing reaponse if "command" in response.keys(): ln = self.redis_client.llen("chain") UDPHandler.sendmessage( json.dumps({ "prev_command": "getchainlength", "body": ln }), response["ip_addr"]) elif "prev_command" in response.keys(): context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) socket.send_string(json.dumps(response)) msg = socket.recv() print(msg)
def get_pupil_time(socket): t1 = time() socket.send_string('t') pct = socket.recv() t2 = time() oneway_dur = (t2 - t1) / 2 return (float(pct.decode()) - oneway_dur) - 0.0005
def start_server(self): """ Start Spyder Remote server. """ if not self._config["enable"]: print("Daemon not enabled. Check configuration!") return # self.start_kernel('/Users/goanpeca/miniconda3/envs/zeroconf') logger.info("Starting daemon!") logging.info("Starting daemon!") context = zmq.Context() socket = context.socket(zmq.REP) self._server_port = find_free_port() socket.bind(f"tcp://*:{self._server_port}") print(f"Bound to port {self._server_port}") self.register_service() while self._running: self._busy = True message = socket.recv() try: reply = self.process_request(message) except Exception as err: reply = json.dumps({"error": str(err)}) print(err) socket.send_string(reply) self._busy = False
def NotifyMachineDataTransfer(src, dst, f_name, client_id): if (dst != None): dst_id, dst_node_addr, dst_node_port = dst with open('config.json') as config_file: data = json.load(config_file) num_ports = data["num_data_node_ports"] src_node_addr = data["data_nodes"]["address"][src - 1] src_node_port_p1 = data["data_nodes"]["management_ports"][ (src - 1) * num_ports] src_node_port_p2 = data["data_nodes"]["management_ports"][ (src - 1) * num_ports] dst_node_port_p2 = data["data_nodes"]["management_ports"][ (dst_id) * num_ports] context = zmq.Context() context2 = zmq.Context() print("send msg to src on port %s" % src_node_port_p2) socket = context.socket(zmq.PAIR) socket.connect( "tcp://%s:%s" % (src_node_addr, src_node_port_p2)) #master connect with them on first port socket.send_string( "send %s %s %s %s" % (f_name, client_id, dst_node_addr, dst_node_port)) #3rd port print("send msg to dst on port %s" % dst_node_port_p2) socket2 = context2.socket(zmq.PAIR) socket2.connect("tcp://%s:%s" % (dst_node_addr, dst_node_port_p2)) socket2.send_string( "recieve %s %s %s %s" % (f_name, client_id, src_node_addr, src_node_port_p1)) return
def threaded_function(self): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(self.url) while True: message = socket.recv() self.queue.put(message) socket.send_string("Ok")
def _cmd_worker(self): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(self.cmd_address) while True: cmd = socket.recv_string() res = self._handle_cmd(cmd) socket.send_string(res)
def send_Req(Host, port): context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://" "%s:%d" % ((Host), port)) print("sending req to the controller A") socket.send_string("Can i join the cluster?") msg = socket.recv(1024) print("Received reply: %s" % msg)
def send_heartbeat(self, socket): if sys.version_info < (3, 0): socket.send("", zmq.SNDMORE) else: socket.send_string("", zmq.SNDMORE) socket.send(struct.pack("<I", MESSAGE_TYPE_HEARTBEAT)) self.event_history.insert(EVENT_HISTORY_SENT_HEARTBEAT) print("Sent heartbeat!")
def threaded_function(self): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(self.url) while True: message = socket.recv() self.queue.put(message) socket.send_string("Ok")
def send_gym(socket, img, reward, done, misc=None, flags=0, copy=True, track=False): if misc is None: misc = {"challenge": None} send_array(socket, img, flags | zmq.SNDMORE, copy, track) socket.send_string(str(reward), flags | zmq.SNDMORE) socket.send_string(str(done), flags | zmq.SNDMORE) return socket.send_string(str(misc), flags)
async def report_sightings( sub_endpoint: str, sightings_queue: asyncio.Queue, transform_cmd: str = None, sink: str = None, ): """ Starts a ZeroMQ publisher on the given endpoint and publishes sightings from the sightings_queue. @param sub_endpoint A host:port string to connect to via ZeroMQ @param sightings_queue The queue to receive sightings from @param transform_cmd The command to use to pipe sightings to. Treated as template string: occurrences of '%ioc' in the cmd string get replaced with the matched IoC. @param report_data If True, only report context data of the sighting instead of the whole thing. """ global logger if transform_cmd: logger.info( f"Using '{transform_cmd}' to transform every sighting's context before sending" ) if sink: logger.info(f"Forwarding sightings to sink '{sink}'") else: socket = zmq.Context().socket(zmq.PUB) socket.connect(f"tcp://{sub_endpoint}") topic = "stix2/sighting" logger.info(f"Forwarding sightings to Threat Bus at {sub_endpoint}/{topic}") while True: sighting = await sightings_queue.get() if type(sighting) is not Sighting: logger.warning( f"Ignoring unknown message type, expected Sighting: {type(sighting)}" ) continue if transform_cmd: sighting = await transform_context(sighting, transform_cmd) if sink: context = ( sighting.x_threatbus_sighting_context if ThreatBusSTIX2Constants.X_THREATBUS_SIGHTING_CONTEXT.value in sighting.object_properties() else None ) if not context: logger.warn( f"Cannot report sighting context to custom sink because no context data is found in the sighting {sighting}" ) continue if sink.lower() == "stdout": print(json.dumps(context)) else: await invoke_cmd_for_context(sink, context) else: socket.send_string(f"{topic} {sighting.serialize()}") sightings_queue.task_done() logger.debug(f"Reported sighting: {sighting}")
def worker_routine(self, worker_url, context: zmq.Context = None): context = context or zmq.Context.instance() socket = context.socket(zmq.REP) socket.connect(worker_url) while True: message = socket.recv_pyobj() socket.send_string("ok") self.qu.put(message)
def test_sync(socket): t1 = time() socket.send_string('t') pct = socket.recv() t2 = time() oneway_dur = (t2 - t1) / 2 corrected_pct = float(pct.decode()) - oneway_dur return t1, corrected_pct, abs(corrected_pct - t1) * 1000 # scale to ms
def reply_for_req_controller(host, port): #Sending req to the response context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://" "%s:%d" % ((host), port)) message = socket.recv(1024) a = message.decode() print(a) socket.send_string("join the database cluster")
def send_alive(): context = zmq.Context() socket = context.socket(zmq.PUB) print("before connect") socket.connect("tcp://%s:%s" % (MASTER_IP, alive_port)) print("alive process connected") while True: message = "%s %s" % (topic_alive, machine_name) socket.send_string(message) sleep(1)
def publish(): while True: with open('./test_topic_files/' + topic + '.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in spamreader: print(', '.join(row)) socket.send_string(topic + " " + str(time.time()) + ' ' + ', '.join(row)) time.sleep(3)
def send_alive(): context = zmq.Context() socket = context.socket(zmq.PUB) socket.connect("tcp://192.168.1.12:%s" % alive_port) while True: # message = [ 1 , socket.gethostbyname(socket.gethostname()) ] message = "%s %s"%(topic_alive , process_order) # socket.send_string(topic , zmq.SNDMORE) socket.send_string(message) print("finished sending alive message") sleep(1)#wait for one second before sending the next alive message
def req_send(): # Do 10 requests, waiting each time for a response with open('./test_topic_files/' + topic + '.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in spamreader: print(', '.join(row)) socket.send_string(topic + " " + str(time.time()) + ' ' + ', '.join(row)) print('Sending ' + topic + " " + str(time.time()) + ' ' + ', '.join(row)) time.sleep(3) message = socket.recv()
def connect_pupil_capture(): """connect to pupil capture using zmq protocol""" context = zmq.Context() socket = zmq.Socket(context, zmq.REQ) socket.connect('tcp://' + ip + ':' + str(port)) socket.send_string('t') if not socket.recv(): print('Cannot connect to Pupil Capture') sys.exit() return socket
def send_container_metadata(self, socket): if sys.version_info < (3, 0): socket.send("", zmq.SNDMORE) else: socket.send("".encode('utf-8'), zmq.SNDMORE) socket.send(struct.pack("<I", MESSAGE_TYPE_NEW_CONTAINER), zmq.SNDMORE) socket.send_string(str(self.model_input_type), zmq.SNDMORE) socket.send_string(str(self.model_output_type), zmq.SNDMORE) socket.send(struct.pack("<I", RPC_VERSION)) self.event_history.insert(EVENT_HISTORY_SENT_CONTAINER_METADATA) print("Sent container metadata!") sys.stdout.flush() sys.stderr.flush()
def on_recv(self, socket, ipc_pub): msg = socket.recv_string() if msg.startswith('notify'): try: payload = zmq_tools.serializer.loads( socket.recv(flags=zmq.NOBLOCK), encoding='utf-8') payload['subject'] except Exception as e: response = 'Notification mal-formatted or missing: {}'.format( e) else: ipc_pub.notify(payload) response = 'Notification recevied.' elif msg == 'SUB_PORT': response = self.g_pool.ipc_sub_url.split(':')[-1] elif msg == 'PUB_PORT': response = self.g_pool.ipc_pub_url.split(':')[-1] elif msg[0] == 'R': try: ipc_pub.notify({ 'subject': 'recording.should_start', 'session_name': msg[2:] }) response = 'OK' except IndexError: response = 'Recording command mal-formatted.' elif msg[0] == 'r': ipc_pub.notify({'subject': 'recording.should_stop'}) response = 'OK' elif msg == 'C': ipc_pub.notify({'subject': 'calibration.should_start'}) response = 'OK' elif msg == 'c': ipc_pub.notify({'subject': 'calibration.should_stop'}) response = 'OK' elif msg[0] == 'T': try: target = float(msg[2:]) except: response = "'{}' cannot be converted to float.".format(msg[2:]) else: raw_time = self.g_pool.get_now() self.g_pool.timebase.value = raw_time - target response = 'Timesync successful.' elif msg[0] == 't': response = repr(self.g_pool.get_timestamp()) elif msg[0] == 'v': response = '{}'.format(self.g_pool.version) else: response = 'Unknown command.' socket.send_string(response)
def on_recv(self, socket, ipc_pub): msg = socket.recv_string() if msg.startswith("notify"): try: payload = zmq_tools.serializer.loads( socket.recv(flags=zmq.NOBLOCK), encoding="utf-8" ) payload["subject"] except Exception as e: response = "Notification mal-formatted or missing: {}".format(e) else: ipc_pub.notify(payload) response = "Notification recevied." elif msg == "SUB_PORT": response = self.g_pool.ipc_sub_url.split(":")[-1] elif msg == "PUB_PORT": response = self.g_pool.ipc_pub_url.split(":")[-1] elif msg[0] == "R": try: ipc_pub.notify( {"subject": "recording.should_start", "session_name": msg[2:]} ) response = "OK" except IndexError: response = "Recording command mal-formatted." elif msg[0] == "r": ipc_pub.notify({"subject": "recording.should_stop"}) response = "OK" elif msg == "C": ipc_pub.notify({"subject": "calibration.should_start"}) response = "OK" elif msg == "c": ipc_pub.notify({"subject": "calibration.should_stop"}) response = "OK" elif msg[0] == "T": try: target = float(msg[2:]) except: response = "'{}' cannot be converted to float.".format(msg[2:]) else: raw_time = self.g_pool.get_now() self.g_pool.timebase.value = raw_time - target response = "Timesync successful." elif msg[0] == "t": response = repr(self.g_pool.get_timestamp()) elif msg[0] == "v": response = "{}".format(self.g_pool.version) else: response = "Unknown command." socket.send_string(response)
def send(self, data): if type(data) is not dict: return False data = json.dumps(data) context = zmq.Context() socket = context.socket(zmq.REQ) socket.setsockopt( zmq.RCVTIMEO, 500 ) socket.connect("tcp://"+self.out_host+":"+self.out_port) print("IDEM SENDOVAT") socket.send_string(data) print("SENDNUTE") message = socket.recv() print(message)
def on_recv(self, socket, ipc_pub): msg = socket.recv_string() if msg.startswith('notify'): try: payload = zmq_tools.serializer.loads(socket.recv(flags=zmq.NOBLOCK), encoding='utf-8') payload['subject'] except Exception as e: response = 'Notification mal-formatted or missing: {}'.format(e) else: ipc_pub.notify(payload) response = 'Notification recevied.' elif msg == 'SUB_PORT': response = self.g_pool.ipc_sub_url.split(':')[-1] elif msg == 'PUB_PORT': response = self.g_pool.ipc_pub_url.split(':')[-1] elif msg[0] == 'R': try: ipc_pub.notify({'subject': 'recording.should_start', 'session_name': msg[2:]}) response = 'OK' except IndexError: response = 'Recording command mal-formatted.' elif msg[0] == 'r': ipc_pub.notify({'subject': 'recording.should_stop'}) response = 'OK' elif msg == 'C': ipc_pub.notify({'subject': 'calibration.should_start'}) response = 'OK' elif msg == 'c': ipc_pub.notify({'subject': 'calibration.should_stop'}) response = 'OK' elif msg == 'a': ipc_pub.notify({'subject':'accuracy_calibration'}) response = 'Set to accuracy calibration' elif msg == 's': ipc_pub.notify({'subject':'screen_marker_calibration'}) response = 'Set to screen marker calibration' elif msg[0] == 'T': try: target = float(msg[2:]) except: response = "'{}' cannot be converted to float.".format(msg[2:]) else: raw_time = self.g_pool.get_now() self.g_pool.timebase.value = raw_time-target response = 'Timesync successful.' elif msg[0] == 't': response = repr(self.g_pool.get_timestamp()) else: response = 'Unknown command.' socket.send_string(response)
def UploadReq(socket, port, messageID, messageName): #print("requesting client ID") #socket.send_string("send ID") clientID = int(messageID) print(clientID) #socket.send_string("send filename") fileName = messageName socket.send_string("filename recieved , send file itself") RecievingFile(fileName, socket) print("file uploaded done") SendingDone(port, fileName, clientID)
def run(self): context = zmq.Context() socket = context.socket(zmq.DEALER) identity = u'worker-%d' % self.id socket.identity = identity.encode('ascii') socket.connect('tcp://localhost:5570') print('Client %s started' % (identity)) poll = zmq.Poller() poll.register(socket, zmq.POLLIN) reqs = 0 while True: reqs = reqs + 1 print('Req #%d sent..' % (reqs)) socket.send_string(u'request #%d' % (reqs)) for i in range(5): sockets = dict(poll.poll(1000)) if socket in sockets: msg = socket.recv() print('Client %s received: %s' % (identity, msg)) socket.close() context.term() return msg
def midas_send(socket, message_type, message, address=None): """ Temporary messasing functions for debuggings. """ if address: socket.send(address, zmq.SNDMORE) socket.send(b"", zmq.SNDMORE) socket.send_string(message) else: socket.send_string(message_type, zmq.SNDMORE) socket.send_string(message)
while True: conn, addr = sock.accept() print("we got connection from", addr) request = conn.recv(1024).decode() print 'Request is ', request f = request.split('GET /')[1].split(' HTTP')[0] print 'File is ', f context = zmq.Context() socket = context.socket(zmq.REQ) port = "5555" socket.connect ("tcp://localhost:%s" % port) socket.send_string(f) message = socket.recv() print "Received reply ", message if message == 'Not found' : mes = '<html><head><title>404 Error</title></head><body><p>Not Found!</p></body><html>' response = 'HTTP/1.1 404 Not Found\r\nContent-Length: ' + str(len(mes)) + '\r\n\r\n'+mes conn.send(response.encode()) else : l = len(message) response = 'HTTP/1.1 200 OK\r\nContent-Length: ' + str(l) + '\r\n\r\n'+message conn.send(response.encode()) conn.close()
def test_resultsServer(): """ tests pyneal.src.resultsServer """ # create settings dictionary settings = {'pynealScannerPort': port, 'pynealHost': host, 'numTimepts': 3, 'launchDashboard': False, 'seriesOutputDir': paths['testDataDir']} scanReceiver = ScanReceiver(settings) scanReceiver.daemon = True scanReceiver.start() # Set up Pyneal Scanner simulator for making a connection to the scanReceiver context = zmq.Context.instance() socket = context.socket(zmq.PAIR) socket.connect('tcp://{}:{}'.format(host, port)) while True: msg = 'hello from test pyneal scanner simulator' socket.send_string(msg) resp = socket.recv_string() if resp == msg: break # Send data to scan receiver ds = nib.load(join(paths['testDataDir'], 'testSeries.nii.gz')) ds_array = ds.get_data() ds_affine = ds.affine for volIdx in range(ds_array.shape[3]): # grab this volume from the dataset thisVol = np.ascontiguousarray(ds_array[:, :, :, volIdx]) # build header volHeader = {'volIdx': volIdx, 'dtype': str(thisVol.dtype), 'shape': thisVol.shape, 'affine': json.dumps(ds_affine.tolist()), 'TR': str(1000)} # send header as json socket.send_json(volHeader, zmq.SNDMORE) # now send the voxel array for this volume socket.send(thisVol, flags=0, copy=False, track=False) # list for response socketResponse = socket.recv_string() # test scanReceiver get functions np.testing.assert_equal(scanReceiver.get_affine(), ds_affine) np.testing.assert_equal(scanReceiver.get_slice(1,10), ds_array[:, :, 10, 1]) np.testing.assert_equal(scanReceiver.get_vol(2), ds_array[:, :, :, 2]) # test saving (then delete) scanReceiver.saveResults() os.remove(join(paths['testDataDir'], 'receivedFunc.nii.gz')) # assuming nothing crashed, shutdown scanReceiver server scanReceiver.killServer()
def get_ip(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('www.google.com', 80)) ip = s.getsockname()[0] s.close() return ip myip = get_ip() socket.connect(args.connect_address) command = 'LIST' socket.send_string(command) peers = socket.recv_multipart()[0].split(' ') cities = """Berlin London Paris Dublin """.splitlines() def get_cities(): for c in cities: if c: yield c def worker(peer):