def __on_bind(self, socket): """Called when the server socket is bound.""" self.port = socket.getsockname()[1] if self.__info_file: with open(self.__info_file, "w") as f: logging.info("Writing info file: %s", self.__info_file) f.write(str(self.port)) logging.info("Listening: %s", socket.getsockname())
def get_nick_for_socket(nick_dico, socket): #get the nickname of a socket try: (ip,a,b,c) = socket.getsockname() #get the ip of the socket res = nick_dictionnary[ip] #check if a nick is linked to this ip except KeyError: #if user doesnt have any nick res = ip return res
def handle(self, socket): self.set_ready() self.logger.debug("Connected to leader") client_address = self.client_hostname or socket.getsockname()[0] socket.send('%s\n' % client_address) # TODO: Use TCP keepalives keepalive = self._server_keepalive(socket) try: for line in util.line_protocol(socket, strip=False): if line == '\n': # Keepalive ack from leader keepalive.kill() keepalive = self._server_keepalive(socket) else: cluster = json.loads(line) if 'leader' in cluster: # Means you have the wrong leader, redirect host = cluster['leader'] port = cluster.get('port', self.leader_address[1]) self.leader_address = (host, port) self.logger.info("Redirected to %s:%s..." % self.leader_address) raise NewLeader() elif client_address in cluster['cluster']: # Only report cluster once I'm a member self.manager.cluster = set(cluster['cluster']) self.manager.trigger_callback() self._leader_election() except NewLeader: self.manager.trigger_callback() if self.leader_address[0] == client_address: self.manager.is_leader = True self.stop() else: return
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 : address = socket.getsockname() print("sending broadcast XML to" + address[0]) print(message) # try to push directly pushTCP(address[0], CLIENT_PORT, message) #also broadcast socket.send(message) #socket.send(str.encode(message)) #socket.send(bytes(message, "utf8")) #encoded = base64.b64encode(bytes(message,'utf-8')) #socket.send( encoded) #time.sleep(4) resp = socket.recv(4096).decode('utf-8') try: print("response is:") print(str(resp)) except Exception as m: # broken socket connection print('broadcast response is borken. exception is: ' + str(m)) except Exception as e: # broken socket connection print('exception by broadcasting! ' + str(e)) socket.close() # broken socket, remove it if socket in SOCKET_LIST: SOCKET_LIST.remove(socket)
def delete_nick(nick_dico,socket): try: (ip,a,b,c) = socket.getsockname() nick_dico[ip] = "Guest" except: print("got an error while deleting a nick") pass
def __init__(self, socket, signal_bus, is_reactive_conn=False): # Validate input. if socket is None: raise ValueError('Invalid arguments passed.') activity_name = ('BgpProtocol %s, %s, %s' % ( is_reactive_conn, socket.getpeername(), socket.getsockname()) ) Activity.__init__(self, name=activity_name) # Intialize instance variables. self._peer = None self._recv_buff = '' self._socket = socket self._signal_bus = signal_bus self._holdtime = None self._keepalive = None self._expiry = None # Add socket to Activity's socket container for managing it. if is_reactive_conn: self._asso_socket_map['passive_conn'] = self._socket else: self._asso_socket_map['active_conn'] = self._socket self._open_msg = None self.state = BGP_FSM_CONNECT self._is_reactive = is_reactive_conn self.sent_open_msg = None self.recv_open_msg = None self._is_bound = False
def get_local_host_ip(self, user_fd=None): if user_fd in self.user_fd_to_socket_fd.keys(): socket = self.socket_fileno_info[ self.user_fd_to_socket_fd[user_fd]]['socket'] try: return socket.getsockname()[0] except Exception as e: logger.error(traceback.format_exc()) return None else: ifconfig_pipe = subprocess.Popen( ['busybox', 'ifconfig', 'wlan0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) ifconfig_info, error = ifconfig_pipe.communicate() ifconfig_pipe.kill() if len(error) != 0: # get wlan0 error return None ifconfig_info = ifconfig_info.decode('utf-8') inet_addr_str = ifconfig_info.split('\n')[1] local_host_ip = None if 'inet addr' in inet_addr_str: local_host_ip = inet_addr_str.split(':')[1].split(' ')[0] return local_host_ip
def __init__(self, socket, signal_bus, is_reactive_conn=False): # Validate input. if socket is None: raise ValueError('Invalid arguments passed.') activity_name = ( 'BgpProtocol %s, %s, %s' % (is_reactive_conn, socket.getpeername(), socket.getsockname())) Activity.__init__(self, name=activity_name) # Intialize instance variables. self._peer = None self._recv_buff = '' self._socket = socket self._socket.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) self._sendlock = semaphore.Semaphore() self._signal_bus = signal_bus self._holdtime = None self._keepalive = None self._expiry = None # Add socket to Activity's socket container for managing it. if is_reactive_conn: self._asso_socket_map['passive_conn'] = self._socket else: self._asso_socket_map['active_conn'] = self._socket self._open_msg = None self.state = BGP_FSM_CONNECT self._is_reactive = is_reactive_conn self.sent_open_msg = None self.recv_open_msg = None self._is_bound = False
def get_free_port(): import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(("", 0)) free_port = socket.getsockname()[1] socket.close() return free_port
def get_unused_port() -> int: import socket s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # just in case s.bind(('', 0)) port = s.getsockname()[1] s.close() return port
def on_close(self, socket): worker = self.workers.pop(socket, None) if worker: self.log.info('%s - %s closed.' % (self.name, worker['name'])) else: host, port = socket.getsockname() self.log.info('%s - socket <%s:%d> closed.' % (self.name, host, port)) return worker
def get_pseudo_header(self, socket): src_host, _src_port = socket.getsockname() dst_host, _dst_port = socket.getpeername() src_quad = [int(i) for i in src_host.split(".")] dst_quad = [int(i) for i in dst_host.split(".")] pseudo_header_info = src_quad + dst_quad + [0, socket.proto, len(self)] pseudo_header_fmt = ("!" "BBBB" "BBBB" "B" "B" "H") return struct.pack(pseudo_header_fmt, *pseudo_header_info)
def __init__(self, socket, HTTPHandler, request_callback=None): HTTPServer.__init__(self, socket.getsockname(), HTTPHandler, False) self.socket = socket self.server_bind = self.server_close = lambda self: None self.HTTPHandler = HTTPHandler self.request_callback = request_callback threading.Thread.__init__(self) self.daemon = True
def _assign(self, socket: socket.socket): self._socket = socket self._host = socket.getsockname() self._remote = socket.getpeername() self._handler = threading.Thread(target=self._receiverHandler, args=(socket, )) self._stop = False self._handler.daemon = True self._handler.start()
def server(interface,port): sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(interface,port)#bind the socket to a public host print('listening for datagrams at {}'.format(socket.getsockname())) while True: data,address=sock.recvfrom(bufsize) text=data.decode('ascii') print('the client at {} says :{!r}'.format(address,text))
def get_addr(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("msn.com", 80)) name = s.getsockname()[0] if name is None: name = socket.getsockname() if name is None: name = "<undefined>" return name
def __init__(self, name, terminal, socket): self.name = name self.terminal = terminal self.terminal.init(self) self.sent = {} self.cameras = [] self.selector = Selector() self.connection = self.selector.register(socket, socket.getsockname()) self.delay = 0.0001
def get_socket_ip(self, socket): if socket == self.node.nodes_node.socket: return self.ip result = socket.getpeername()[0] if result == self.ip: result = socket.getsockname()[0] return result
def leave_channel(socket,channel_to_leave): (ip,a,b,c) = socket.getsockname() #get the ip of the socket and some useless informations print(ip + "left the channel " + channel_to_leave) try: channel_dictionnary[ip].remove(channel_to_leave) #we remove the channel to the channel list linked to this ip res = "Vous avez quitté le channel " + str(channel_to_leave) +"\n" socket.send(res.encode()) #we inform the user that he just left the channel broadcast_on_channel((ip+" left the channel "+channel_to_leave+"\n"), channel_to_leave, socket_list)#we broadcast a msg to the channel which inform the users that one has left except ValueError: #if the channel_name isnt on the list linked to this ip of the dictionnary print("you are not on this channel")
def port(socket,portnumber): high,low = splitBytes(portnumber) client = socket.getsockname()[0] octet = client.split('.') socket.send(bytes('PORT '+octet[0]+','+octet[1]+','+octet[2]+','+octet[3]+','+str(high)+','+str(low),'ASCII')+b'\x0d\x0a') data = socket.recv(1024) print(data.decode('ASCII'),end='') if int(data.decode('ASCII')[:3]) == 200: return True else: return False
async def start(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((self.hostname, self.port)) if self.port == 0: self.port = socket.getsockname()[1] tls_context = self.tls_context if self.use_tls else None self.server = await asyncio.start_server(self.on_connect, ssl=tls_context, sock=sock, loop=self.loop)
def __init__(self, socket: socket.socket, servidor: object): ''' Método construtor da classe Par :parameter socket: socket pelo qual o par se comunica :parameter servidor: servidor ''' threading.Thread.__init__(self) self.__socket = socket self.__servidor = servidor self.__name = str(socket.getsockname()) self.start()
def handle_request(socket, client_address, server): s = ServerInfo(software=server_version, multiconnection=True, multithread=False, multiprocess=False) c = ConnectionInfo(server=s) c.server.addr = LazyAddress(socket.family, lambda: socket.getsockname()) c.remote.addr = Address(socket.family, client_address) c.socket = socket with socket.makefile('r') as input: with socket.makefile('w') as output: app(input, output, sys.stderr, c)
def do_Send(): global currentState, user inputData = userentry.get() if len(inputData.strip(' ')) == 0: print('Detect nothing to send!\n') return CmdWin.insert(1.0, "\nPress Send") # check stage stateLock.acquire() checkFlag = currentState.isAfter(States['NAMED']) stateLock.release() if not checkFlag: CmdWin.insert(1.0, "\nSend Error: You are not in any chatroom, please join a chatroom first!") return # check for all back and forward link sendingList = [] stateLock.acquire() forwardLinkTuple = currentState._getforwardlink() if forwardLinkTuple is not None: forwardLink = forwardLinkTuple[1] sendingList.append(forwardLink) backwardLinkTupleList = currentState._getbackwardlinks() backwardLinks = [i[1] for i in backwardLinkTupleList] roomName = currentState._getroomname() stateLock.release() if len(backwardLinks) > 0 : sendingList = sendingList + backwardLinks # get all infos desired by sending Text message userInfoLock.acquire() userName = user._getname() userIp = user._getip() userPort = user._getport() # update msgID msgID = currentState.newMsgID() userInfoLock.release() # construct the protocal message originHID = sdbm_hash(userName+userIp+str(userPort)) message = [roomName, str(originHID), userName, str(msgID), str(len(inputData)), inputData] requestMessage = 'T:' + ':'.join(message) + PROTOCAL_END print("\nMain Thread: perform the sending process, dispatch data to other peers\n") print('Message:', requestMessage) for socket in sendingList: output = socketOperation(socket, requestMessage, receive = False) if output == Exceptions['SOCKET_ERROR']: print('Send Error: cannot sent the message to', socket.getsockname()) MsgWin.insert(1.0, '\n['+userName+']: '+inputData) # clear the entry if success userentry.delete(0, END)
def handshake(socket): socket.send(createMessage(msg_type=MSG_JOIN, org_ip=socket.getsockname()[0])) response = socket.recv(1024) header, payload = parseReceivedMessage(response) # Join was successful if payload == ('0200'): global neighbours neighbours.append((header[6], header[4])) # Send PING type b to expand neighbourhood socket.send(createMessage(ttl=5, org_port=socket.getsockname()[1], org_ip=socket.getsockname()[0])) response = socket.recv(1024) header, payload = parseReceivedMessage(response) if len(payload) > 0: # Iterate through payload for i in range(1, len(payload)): # Add to neighbours if not already there if not (payload[i][0], payload[i][1]) in neighbours: neighbours.append((payload[i][0], payload[i][1])) print("Neighbours:") print(neighbours)
def _bind_socket(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.bind((self.hostname, self.port)) except OSError: logger.exception("Error occurred binding to %s on port %s", self.hostname, self.port) raise if self.port == 0: self.port = socket.getsockname()[1] return sock
def __init__(self, socket): gps.GPSTransport.__init__(self) self.address = '%s:%s' % socket.getpeername() self.localaddress = '%s:%s' % socket.getsockname() self.socket = socket self.closeReason = None self.socketStatsEnabled = prefs.GetValue('socketStatsEnabled', False) self.statsBytesReadPerPacket = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESREADPERPACKET_PERIODS) self.statsBytesWrittenPerPacket = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESWRITTENPERPACKET_PERIODS) self.statsBytesRead = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESREAD_PERIODS) self.statsBytesWritten = macho.EWMA.FromSampleCounts(GPSSTATS_BYTESWRITTEN_PERIODS) self.statsPacketsRead = macho.EWMA.FromSampleCounts(GPSSTATS_PACKETSREAD_PERIODS) self.statsPacketsWritten = macho.EWMA.FromSampleCounts(GPSSTATS_PACKETSWRITTEN_PERIODS)
def cmd(socket, command_message): socket.send('2') prompt_str = socket.getsockname()[0] + ':' + str(socket.getsockname()[1]) while True: try: print 'cmd mode' command = raw_input(prompt_str + ">") if len(command.split()) != 0: socket.send(command) else: continue except EOFError: print( "Invalid input, type 'help' to get a list of implemented commands.\n" ) continue if command == "quit": break data = socket.recv(SOCKET_RECV_BYTES) print(data + "\n")
def send_packet(socket, priority, poll, others, pdns): others_list = {} #pdns_list = [] for o in others: #print socket.getpeername(), others[o] others_list[others[o]['ip']] = others[o]['priority'] #for p in json.loads(pdns.value): # pdns_list.append(p['ip']) packet = { 'ip': socket.getsockname()[0], 'priority': priority.value, 'last_poll': poll.value, 'known_others': others_list } #'known_pdns': json.loads(pdns.value) } socket.sendall(json.dumps(packet)+"EOT")
def InputCmd(self,socket,port): #此处使用的是控制信道 state = True addr, socport = socket.getsockname() dataport = Createport() socket.send(b"DataPort="+bytes(dataport)) while state: cmd = input('请输入命令') socket.send(bytes(cmd, encoding="utf-8")) ##传输命令到服务器端 result = socket.recv(1024) if result == b"0": state = False print("you are quit") else: DataTranfer(dataport,host,cmd)
def serveClient(self, key): clientSocket = key.fileobj data = key.data recivedData = clientSocket.recv(512) if (len(recivedData) > 0): print(f'Recived Data : {str(recivedData,ENCODIING)}') self.broadCastSend( f'{data["userName"]}:{str(recivedData,ENCODIING)}') else: print(f'Closing connection to{data["adress"]}') sel.unregister(clientSocket) for i, socket in enumerate(self.clients): if (socket.getsockname()[1] == clientSocket.getsockname()[1]): del self.clients[i] clientSocket.close()
def keep_socket_connection(socket): failed_attempts = 0 while True: print "running" try: socket.send(' ') failed_attempts = 0 except: if failed_attempts < NUM_OR_RETRIES: print 'Retry connecting to {socket} '.format(socket=socket) failed_attempts += 1 else: break # stop retrying sleep(1) print 'close connection the socket ', socket.getsockname()
def is_remote_mitm_server(self, host, port): """Check if the remote host:port is one of the MiTM server sockets. These connections should be avoided otherwise loops can be created where the MiTM tries to connect to the MiTM which then sees the remote as the MiTM and tries to connection and so on. This is best effort only, routing can still cause these loops. Returns if host:port belongs to one of the server sockets.""" local_v4, local_v6 = util.get_interface_addresses() if host in local_v4 or host in local_v6: for socket in self._local_server_sockets: local = socket.getsockname() if local[1] == port: return True 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 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 __init__(self, workerid, ppid, socket, app, timeout): self.id = workerid self.ppid = ppid self.timeout = timeout fd, tmpname = tempfile.mkstemp() self.tmp = os.fdopen(fd, "r+b") self.tmpname = tmpname # prevent inherientence self.close_on_exec(socket) self.close_on_exec(fd) self.socket = socket self.address = socket.getsockname() self.app = app self.alive = True self.log = logging.getLogger(__name__)
def __init__(self, socket, authtoken, handler=None, server=None): """Create a new message bus connection. The `socket` argument must be a connected socket and the `authtoken` argument must be the shared secret for hmac-magic-cookie-sha1 authentication. The `handler` argument, if provided, must be a MessageBusHandler instance that will be used to dispatch signals and method calls. If no handler is provided, signals and method calls to this connection end point will be ignored. The `server` argument, if provided, must be a MessageBusServer instance, and incidates that this connection is a server connection. Without a server argument this connection will be a client connection. """ self.socket = socket self.authtoken = authtoken self.handler = handler self.server = server if self.server is None: self.name = str(socket.getsockname()) else: self.name = self.server.name self.peer_name = str(socket.getpeername()) self.next_serial = 1 self.closed = False self.tracefile = None self.callbacks = [] logger = logging.getLogger('bluepass.messagebus') context = 'connection %s:%s' % (self.name, self.peer_name) self.logger = logging.ContextLogger(logger, context) self.loop = self.Loop() self.method_calls = {} self._read_event = self.loop.create_watch(socket, self.loop.READ, self._do_read) self._write_event = self.loop.create_watch(socket, self.loop.WRITE, self._do_write) self._inbuf = self._outbuf = '' self._incoming = []; self._outgoing = [] self._reading = self._writing = True
def get_port(socket): """Return the port to which a socket is bound.""" addr, port = socket.getsockname() return port
def __init__(self, socket, proto): self.host = socket.getsockname() self.peer = socket.getpeername() self.protocall = proto self.recevied_time = time.time()
def test_tcp_listener(self): socket = eventlet.listen(('0.0.0.0', 0)) assert socket.getsockname()[0] == '0.0.0.0' socket.close() check_hub()
''' 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 listenIp = "0.0.0.0" listenPort = 123 socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) socket.bind((listenIp,listenPort)) print "local socket: ", socket.getsockname(); recvThread = RecvThread(socket) recvThread.start() workThread = WorkThread(socket) workThread.start() while True: try: time.sleep(0.5) except KeyboardInterrupt: print "Exiting..." stopFlag = True recvThread.join() workThread.join() #socket.close() print "Exited"
def process_message(header, payload, socket): # Discard messages with invalid version or ttl global q_searches global connections global neighbours if (header[0] == 1 or header[1] < 1 or header[1] > 5): if header[2] == MSG_PING: # Type a if header[1] == 1: print("Respond with PONG A") socket.send(createMessage(msg_type=MSG_PONG, org_port=socket.getsockname()[1], org_ip=socket.getsockname()[0])) # Type b else: tmp = list(neighbours) if (header[6], header[4]) in tmp: tmp.remove((header[6], header[4])) response = tmp[:5] data = bytearray() if(len(response) > 0): data.extend(struct.pack('>HH', len(response), 0)) for item in response: data.extend(struct.pack('>IHH', ipToNum(item[0]), item[1], 0)) print("Respond with PONG B") socket.send(createMessage(msg_type=MSG_PONG, org_port=socket.getsockname()[1], org_ip=socket.getsockname()[0], payload=data)) elif header[2] == MSG_PONG: # Pong type b if len(payload) > 0: # Iterate through payload for i in range(1, len(payload)): # Add to neighbours if not already there if not (payload[i][0], payload[i][1]) in neighbours: neighbours.append((payload[i][0], payload[i][1])) elif header[2] == MSG_BYE: if (header[6], header[4]) in neighbours: neighbours.remove((header[6], header[4])) print("Neighbours:") print(neighbours) if (header[6], socket) in connections: connections.remove((header[6], socket)) elif header[2] == MSG_JOIN: if not (header[6], header[4]) in neighbours: neighbours.append((header[6], header[4])) print("Neighbours:") print(neighbours) data = bytearray() data.append(0x02) data.append(0x00) print("Respond with JOIN OK") socket.send(createMessage(msg_type=MSG_JOIN, org_port=socket.getsockname()[1], org_ip=socket.getsockname()[0], payload=data)) elif header[2] == MSG_QUERY: # Check if key is known if payload[0] in keys: data = struct.pack('>HHHH4s', 1, 0, 1, 0, binascii.unhexlify(keys[payload[0]])) print("Respond with QUERY HIT") socket.send(createMessage(msg_type=MSG_QHIT, org_port=socket.getsockname()[1], org_ip=socket.getsockname()[0], payload=data, msg_id=header[7])) # Save search q_searches.append((header[6], header[7])) # Forward to other nodes forward(header, payload, socket) elif header[2] == MSG_QHIT: # Check if known message id for (x, y) in q_searches: if y == header[7]: # Check if connection exists with given ip address for (a, b) in connections: if a == x: data = bytearray() data.extend(struct.pack('>HH', payload[0], 0)) for i in range(payload[0]): data.extend( struct.pack('>HH4s', i+1, 0, binascii.unhexlify( payload[1][i+1]))) b.send(createMessage(msg_type=MSG_QHIT, org_port=header[4], org_ip=header[6], payload=data, msg_id=y))
def recvFrom(self, socket): print "Listening on ".format(socket.getsockname()) while True: chunk = self.readChunk(socket) audio = self.netToAudio.convert(chunk) self.speaker.play(audio)