def stop_service(self): """ properly kills the process: https://stackoverflow.com/a/16736227/4225229 """ self.running = False socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((self.hostname, self.port)) self.socket.close()
def __init__(self, s_addr: str, r_addr: str, s_port: int, r_port: int): super().__init__() # Send Socket (CMD) if (s_port > 0): self.s_send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.send_addr = (s_addr, s_port) # Receive Socket (TLM) if (r_port > 0): self.s_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s_recv.bind((r_addr, r_port))
def findNextConsecutivePorts(port,IF=''): import socket while 1: try: sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) sock1.bind((IF, port)) sock2.bind((IF, port+1)) sock1.close() sock2.close() break except socket.error: port=port+2 return port
def __init__(self): super().__init__() import socket if os.name == 'posix': self._putsoket, self._getsocket = socket.socketpair() else: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('127.0.0.1', 0)) server.listen(1) self._putsoket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._putsoket.connect(server.getsockname()) # print(server.getsockname()) self._getsocket, self.addr = server.accept() server.close()
def worker(server_address): serv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) serv.connect(server_address) while True: fd = recv_fd(serv) print('WORKER: GOT FD', fd) with socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd) as client: while True: msg = client.recv(1024) if not msg: break print('WORKER: RECV {!r}'.format(msg)) client.send(msg)
def handle_telnet(address, config_obj): s = socket.socket(AF_INET, SOCK_STREAM) # initialize tcp socket name, port = address #print ('*** Telnet Server starting up on %s port %s\n' % address) INTERACTIONS.put({ 'type': 'info', 'message': 'Telnet Server starting up on %s port %s' % address, 'time': get_time() }) s.bind(address) # binds socket to address and port s.listen(1) # start listening finger = config_obj.get('mainset', 'p0f') # check if p0f is enabled in config capture = config_obj.get('mainset', 'writepcap') # start scapy sniffing and packet capture if capture is enabled in config file if capture == 'True': pcappackets = config_obj.get('mainset', 'pcappackets') if pcappackets: pcappackets = int(pcappackets) else: pcappackets = 100 sniff_stdout = config_obj.get('mainset', 'sniff_stdout') # call up scapy sniffing in new thread start_new_thread(record_packets, (pcappackets, port, sniff_stdout)) # get banner and other data from config file to display to client banner = config_obj.get('telnet_srv', 'banner') cmdline = config_obj.get('authentication', 'username') + ' ' + config_obj.get( 'telnet_srv', 'input_sym') + ' ' INTERACTIONS.put({ 'type': 'info', 'message': 'Waiting for a connection on port %s' % port, 'time': get_time() }) # Wait for connections while 1: try: c, a = s.accept() # accept incoming connection #print('Got connection', c, a) clientip = a[0] conn_obj = { 'type': 'client-connect', 'message': 'telnet', 'ip': clientip, 'time': get_time() } INTERACTIONS.put(conn_obj) # get device fingerprint of the incoming connection, multithreaded if finger == 'True': start_new_thread(fingerprint, (clientip, )) # handle client request, multithreaded start_new_thread(telnet_response, (c, a, banner, cmdline, config_obj)) except Exception as e: print('{}: {}'.format(e.__class__.__name__, e))
def run_client_sniff(host='127.0.0.1', port=1234): sock = socket.socket() sock.connect((host, port)) sniff( store=False, prn=lambda pkt: sock.sendall(struct.pack('>H', len(pkt)) + raw(pkt)) )
def main(): mongoClient = MongoClient('localhost', 27017) db = mongoClient.arduino # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_address = ('0.0.0.0', 8080) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) # Listen for incoming connections sock.listen(1) finish = False; while not finish: # Wait for a connection print >>sys.stderr, 'waiting for a connection' s, client_address = sock.accept() print >>sys.stderr, 'accepted connection from ', str(client_address) timeval = struct.pack("4I", 60*5, 0, 0, 0) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, timeval) s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval) try: server = Server(s, db) t = Thread(target = server.serveOneClient) t.setDaemon(True) t.start(); except Exception as e: print(e.__doc__) print(e.message)
def getLatestOrderlistfromClient(self): for x in range(len(self.clientlist)): client_ip, client_port = self.clientlist[x] client_order_request_port = client_port + 200 # port listening for requests for missed orders s = socket.socket(AF_INET, SOCK_STREAM) # create one heartbeat TCP socket for each server s.settimeout(2) # set timeout for every socket to 2 seconds leader_ordernumber_msg = pickle.dumps(self.ordernumber) try: s.connect((client_ip, client_order_request_port)) # Connect to every servers socket to inform about new leader s.send(leader_ordernumber_msg) response = s.recv(1024) try: #if the client has no higher orderid response will be 'no' which is string response = response.decode() print('Client',self.clientlist[x], 'has no missed orders') except: # if response can not be decoded it means it's no string. It will be list of missed orders missed_order_list = [] missed_order_list = pickle.loads(response) for i in range(len(missed_order_list)): self.orderlist.append(missed_order_list[i]) self.ordernumber += 1 print('Client', self.clientlist[x], 'has sent', len(missed_order_list), 'missed orders') self.orderlist.sort(key=lambda x: x[0]) # after adding missed orders. Sort orderlist except: pass # if connection cant be establish client is offline print('Latest orderlist:', self.orderlist)
def listenServerListUpdate(self): # Listening for serverlist updates server_address = ('', ServerlistUpdatePort) sock = socket.socket(AF_INET, SOCK_STREAM) # TCP socket sock.bind(server_address) # Bind to the server address sock.listen() while True: connection, leader_address = sock.accept() # Wait for a connection leaderserverlist = connection.recv(2048) # save incoming bytes leaderserverlist = pickle.loads(leaderserverlist) # unpickle the message newserverlist = [] newserverlist = leaderserverlist # store leaderserverlist in new list serverlist_lenght = len(newserverlist) # store lenght of newserverlist in variable for x in range(serverlist_lenght): connection_and_leader = newserverlist[x] # serverlist format: ((host ip, port, true/false) server_adress, isLeader = connection_and_leader # split up tuple into sinlge variables ip, port = server_adress # split up server_adress into ip adress and port if ip == host_ip_address: # remove own ip from list del newserverlist[x] newserverlist.append((leader_address, True)) # add leader server to list self.serverlist = newserverlist # Overwrite own list with new one sleep(0.5) # just to print Receveived Multicast msg from leader before starting heartbeat message self.updateServerList(self.serverlist) # Overwrite old serverlist with the updated list
def __init__(self, host2, port2): # client socket self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection = None # client condition self.connected = False # while client haven't connected to server while not (self.connected): try: # reconnecting to server self.client_socket.connect((host2, port2)) self.connection = self.client_socket.makefile('wb') self.connected = True # if failed except Exception as e: # if kill switch is activated if (LatchingSwitch.tr_alive != True): # stop trying self.connected = True # if kill switch is not activated else: # try again pass # execute client sending self.sending()
def listenforOrderlistUpdate(self): # Thread 10 # Listening Orderlist with Server server_address = ('', UpdateOrderlistPort) sock = socket.socket(AF_INET, SOCK_STREAM) # TCP socket sock.bind(server_address) # Bind to the server address sock.listen() while True: connection, server_address = sock.accept() # Wait for a connection leader_ordernumber = connection.recv(1024) leader_ordernumber = pickle.loads(leader_ordernumber) # unpickle the order number and compare to own if leader_ordernumber > self.ordernumber: # if leader has more orders than ask for the missing orders own_ordernumber = pickle.dumps(self.ordernumber) # send own ordernumber connection.send(own_ordernumber) for i in range(leader_ordernumber-self.ordernumber): missing_order = connection.recv(1024) # wait for missing order missing_order = pickle.loads(missing_order) ack_msg_missing_order = 'Received missing order' connection.send(ack_msg_missing_order.encode()) self.orderlist.append(missing_order) # add missing order in own list self.ordernumber += 1 # count up own ordernumber print('Received missing updates from leader server. Current orderlist: ', self.orderlist) else: msg = 'no' msg = pickle.dumps(msg) connection.send(msg)
def __init__(self, host2, port2): # assign value to shared data variable RangeFinderServer.brake = True RangeFinderServer.warning = [] # server socket and port self.server_socket = socket.socket() self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((host2, port2)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # while VideoStreamServer.color is still empty while (VideoStreamServer.color == []): # if kill switch for threading is activated if (LatchingSwitch.tr_alive != True): # break from while loop break # rest for 0.1 second time.sleep(0.1) # execute server receiving self.receiving()
def driver_initial(): """ 初始化浏览器对象并序列化 :return: """ client_socket = socket.socket(AF_INET, SOCK_STREAM) try: # setdefaulttimeout(1) 导致启动浏览器异常 设为较大时间 如 10 无异常 client_socket.settimeout(2) client_socket.connect(('127.0.0.1', 4444)) client_socket.close() print('4444端口已占用,geckodriver已启动') return True except Exception as e: print('Error :', e) print('4444端口未占用,geckodriver未启动') ShellExecute(0, 'open', 'geckodriver', '', '', 1) # ShellExecute(hwnd, op, file, params, dir, bShow) # 其参数含义如下所示。 # hwnd:父窗口的句柄,如果没有父窗口,则为0。 # op:要进行的操作,为“open”、“print”或者为空。 # file:要运行的程序,或者打开的脚本。 # params:要向程序传递的参数,如果打开的为文件,则为空。 # dir:程序初始化的目录。 # bShow:是否显示窗口。 # firefox.exe -ProfileManager -no-remote driver = webdriver.remote.webdriver.WebDriver( command_executor="http://127.0.0.1:4444", browser_profile=FirefoxProfile(FIREFOX_DIR), desired_capabilities=DesiredCapabilities.FIREFOX) # driver.get('about:blank') put_browser(driver) return False
def getLatestOrderlistfromServer(self): for x in range(len(self.serverlist)): connection_and_leader = self.serverlist[x] # serverlist consists a tuple of a tuple and a boolean. The inside tuple are the connection details host ip and port server_adress, isLeader = connection_and_leader # split up tuple into sinlge variables ip, port = server_adress # split up server_adress into ip adress and port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create one heartbeat TCP socket for each server s.settimeout(2) # set timeout for every socket to 1 seconds try: s.connect((ip, SendOrderlistToNewLeaderPort)) # Connect to each member server ordernumber = pickle.dumps(self.ordernumber) s.send(ordernumber) # send ordernumber and wait for the response response = s.recv(1024) try: response = pickle.loads(response) except: response = response.decode() if response == 'no': print('New Leader: Orderlist of leader server and server', ip, ' is identical') else: self.orderlist = response self.ordernumber = len(self.orderlist) print('Restored latest list form server', ip) print('Current orderlist:', self.orderlist, 'Current ordernumber:',self.ordernumber) except: print('Could not connect or send msg to:', ip, ',', SendOrderlistToNewLeaderPort) finally: s.close()
def __init__(self, ip_addr="172.20.10.10"): self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect((ip_addr, 6000)) self.vsock = videosocket.videosocket(self.client_socket) self.videofeed = VideoFeed(1, "client", 1) self.data = StringIO.StringIO()
def __init__(self, host1, port1): # client socket self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection = None # client condition self.connected = False # while client haven't connected to server while not (self.connected): try: # reconnecting to server self.client_socket.connect((host1, port1)) self.connection = self.client_socket.makefile('wb') self.connected = True except Exception as e: # if failed try again pass # execute client sending self.sending()
def listenforNewLeaderMessage(self): # Thread 5: Listening to NewLeaderMessage server_address = ('', NewLeaderMessagePort) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(server_address) sock.listen() # Listening to NewLeaderMessage while True: connection, server_address = sock.accept() newleader_ip = connection.recv(1024) newleader_ip = newleader_ip.decode() for i in range(len(self.serverlist)): # search for the leader IP in the serverlist connection_and_leader = self.serverlist[i] # serverlist consists a tuple of a tuple and a boolean. The inside tuple are the connection details host ip and port server_adress, isLeader = connection_and_leader # split up tuple into sinlge variables ip, port = server_adress # split up server_adress into ip adress and port if ip == newleader_ip: # When ip in list matches the leader ip change the isLeader value to True self.serverlist[i] = server_adress, True # Overwrite old value with new value response = 'ack msg.Received new leader information' # send back ack msg connection.send(response.encode()) newleadderID = newleader_ip.split('.') print('Received newLeaderMessage: new leader is:', newleadderID[3]) print('Updated my serverlist: ', self.serverlist)
def sendUpdatedClientList(self): # Function can only used by leader server if self.isLeader == True: if len(self.serverlist)>0: # if server list consists at least one server replicate the updated client list for x in range(len(self.serverlist)): # send new client to all replica servers in list connection_and_leader = self.serverlist[x] # host ip and port and True/False server_adress, isLeader = connection_and_leader # split tuple ip, port = server_adress # split server_adress s = socket.socket(AF_INET, SOCK_STREAM) # create one heartbeat TCP socket for each server s.settimeout(3) # wait 3 seconds for respond message1 = pickle.dumps(self.clientlist_counter) message2 = pickle.dumps(self.clientlist) # pickle to send objects try: s.connect((ip, ClientListUpdateServerPort)) # Connect to Client list update port s.send(message1) try: response = s.recv(1024) response = response.decode() if response=='yes': s.send(message2) print("Client list has been sent to : {},{} ".format(ip, ClientListUpdateServerPort)) else: print("Server {} already knows the client. Rejected client") except socket.timeout: print('No response received from sent clientlist_counter from:{}'.format(ip)) except Exception as e: print(e) print("Failed to send clientlist to: {},{}".format(ip, ClientListUpdateServerPort)) finally: s.close() else: print("Serverlist is Empty cant replicate clientlist to member servers")
def listenClientListUpdate(self): # Thread 3: Listening for clientlist updates server_address = ('', ClientListUpdateServerPort) sock = socket.socket(AF_INET, SOCK_STREAM) # TCP socket sock.bind(server_address) sock.listen() while True: connection, server_address = sock.accept() message1 = connection.recv(1024) message1 = pickle.loads(message1) new_clientlist_counter = message1 if new_clientlist_counter[0]> self.clientlist_counter[0] or new_clientlist_counter[1]> self.clientlist_counter[1] : response = 'yes' response = response.encode() connection.send(response) message2 = connection.recv(1024) message2 = pickle.loads(message2) self.clientlist = message2 self.clientlist_counter = new_clientlist_counter print('Received update from leader. Clientlist: ', self.clientlist) else: response = 'no' response = response.encode() connection.send(response) print('Rejected client list update')
def sendUpdatedServerList(self): if self.isLeader is True: if len(self.serverlist) > 0: # if server list consists a server replicate the updated client list to the servers for x in range(len(self.serverlist)): # send new clients to all replica servers in list connection_and_leader = self.serverlist[x] # host ip, port, true/false server_adress, isLeader = connection_and_leader # split up tuple into sinlge variables ip, port = server_adress # split up server_adress into ip adress and port s = socket.socket(AF_INET, SOCK_STREAM) # create one heartbeat TCP socket for each server s.settimeout(3) # wait 3 seconds for respond try: s.connect((ip, ServerlistUpdatePort)) # Connect to Client list update port updatedserverlist = pickle.dumps(self.serverlist) # send updated serverlist s.send(updatedserverlist) try: response = s.recv(1024) response = response.decode() except socket.timeout: #print('No response received from sent serverlist from: {}'.format(ip)) pass except: print("Failed to send serverlist to: {}".format(ip)) finally: s.close() else: print("Serverlist is Empty cant replicate serverlist to member servers")
def _check_bind(port): with socket.socket() as s: try: s.bind(('', port)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return port except OSError: return None
def sendPacket(self, dstPort): try: conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.connect((self.dstIP, dstPort)) self.queue.put(dstPort) conn.close() except: pass
def __init__(self, adress, port): self.MCAST_GRP = adress self.MCAST_PORT = port self.MulticastSockect = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.MulticastSockect.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
def Connection(ip, port, time=6): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(time) result = sock.connect_ex((ip, int(port))) if result == 0: print("Port open: " + str(port)) else: print("Prot close: " + str(port)) sock.close()
def broadcast(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) while True: s.sendto('this is testing'.encode('utf-8'), ('255.255.255.255', 12345)) import time time.sleep(1)
def get_current_ip(): import socket ip = (([ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0] return ip
def listen_for_command(): receive_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) receive_socket.bind(('', HONEYNODE_COMMAND_PORT)) data, addr = receive_socket.recvfrom(1024) data = data.decode('utf-8') data = json.loads(data) print("data: {} from {}".format(data, addr)) if data['command'] == 'KILL': kill()
def broadcast_receive(): import socket client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) client.bind(("", 37020)) while True: data, addr = client.recvfrom(1024) print("received message: %s" % data)
def port_alive(ip, port): socket.setdefaulttimeout(1) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex((ip, port)) if result == 0 : return True s.close() return False
def startHeartbeat(self): message = ('Heartbeat') failed_server = -1 # initial value -1 means there is no failed server while self.heartbeatActive: sleep(3) # failure detection every 3 seconds for x in range(len(self.serverlist)): if self.servermemberUpdate is True: self.heartbeatActive = False break connection_and_leader = self.serverlist[x] server_adress, isLeader = connection_and_leader # split up tuple into sinlge variables ip, port = server_adress # split up server_adress into ip adress and port s = socket.socket(AF_INET, SOCK_STREAM) # create one heartbeat TCP socket for each server s.settimeout(2) # set timeout for every socket to 1 seconds try: s.connect((ip, UnicastServerPort)) # Connect each socket to ip adress and UNICAST Port s.send(message.encode()) # Sending Heartbeat: Heartbeatmsg sent to: {},{} ".format(ip, UnicastServerPort)) try: response = s.recv(1024) # print(response) except socket.timeout: # No response pass # if no response is received remove server from list except: # Server can't connect failed_server = x # Position of failed server in the server list if isLeader is True: # Crashed server is the leader self.leaderCrashed = True # print ('Leader crashed') finally: s.close() if failed_server >= 0: # If a failed server is detected newserverlist = self.serverlist del newserverlist[failed_server] if self.leaderCrashed is True: print('Removed crashed leader server', ip, 'from serverlist') else: print('Removed crashed server', ip, 'from serverlist') self.updateServerList(newserverlist) self.heartbeatActive = False # check if heartbeatActive value has changed if self.heartbeatActive is False: # everytime serverlist is updated self.heartbeatActive will set to False to end thread break #print('Stopped Heartbeat!') self.restartHeartbeat()
def accept_broadcast(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.bind(('', 12345)) m = s.recvfrom(1024) print(m) global SERVER_ADDRESS SERVER_ADDRESS = m[1][0] except: pass
def server( address, id_p, out_p, worker_pid): in_p.close() s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) s.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, True) s.bind(address) s.listen(1) while True: client, addr = s.accept() print( 'SERVER: Got connection from ', addr) send_handle(out_p, client.fileno(), worker_pid) client.close()
def get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 1)) IP = s.getsockname()[0] except Exception: IP = '127.0.0.1' finally: s.close() return IP
def worker( in_p, out_p): out_p.close() while True: fd = recv_handle(in_p) print( 'CHILD: GOT FD ', fd) with socket.socket( socket.AF_INET, socket.SOCK_STREAM, fileno = fd) as s: while True: msg = s.recv(1024) if not msg: break print( 'CHILD: RECV {!r}'.format(msg)) s.send(msg)
def post(): sock = socket.socket() sock.connect((host, port)) logger.info("POST %s", args.url) sock.sendall('POST %s HTTP/1.1\r\n' % url.path) sock.sendall('Host: %s\r\n' % url.netloc) sock.sendall('Accept: */*\r\n') sock.sendall('\r\n') for data in read_tun(tun): logger.debug('> %dB', len(data)) sock.sendall(data) logger.warning("quit post")
def dns_test(addr): s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) s.settimeout(TIMEOUT) # send DNS question to server sendcount=s.sendto(TEST_QUERY, 0, (addr,DNS_PORT)) if sendcount <= 0: return False # wait for response try: recvdata=s.recvfrom(1024) print(recvdata) except socket.error, e: print(e) return False
def get(): sock = socket.socket() sock.connect((host, port)) logger.info("GET %s", args.url) sock.sendall('GET %s HTTP/1.1\r\n' % url.path) sock.sendall('Host: %s\r\n' % url.netloc) sock.sendall('Accept: */*\r\n') sock.sendall('\r\n') f = sock.makefile('r', 0) while f.readline().strip(): # read until blank line pass for data in read_connection(f): logger.debug('< %dB', len(data)) os.write(tun.fd, data) logger.warning("quit get")
def command_server(): global c, cmd_socket, is_exiting cmd_socket = socket.socket(AF_INET, SOCK_STREAM) cmd_socket.bind((HOST, SOCKET_PORT)) cmd_socket.listen(5) while not is_exiting.isSet(): logging.debug("accepting") (conn, addr) = cmd_socket.accept() logging.debug("accepted") received = conn.recv(4) if not received: continue length, = unpack("<i", received) if length <= 0 or length > MAX_LENGTH: logging.warning("invalid header: {0}".format(length)) conn.close() # invalid header continue try:# mesg = json.loads(conn.recv(length)) if not isinstance(mesg, dict): logging.warning("not a javascript object") continue if not mesg.has_key("action"): raise ActionError("action not specified") logging.info("action: {0}".format(mesg["action"])) try: lock.acquire_write() conn.send(action_map[mesg["action"]](mesg)) finally: lock.release() except ValueError: logging.warning("malformed json string") except ActionError as e: logging.warning(e) except KeyError as e: logging.warning("action not found: {0}".format(mesg["action"])) except SocketError as e: logging.warning("socket error: {0}".format(e)) finally: conn.close()
def __init__(self, dev=DEFAULT_IP, recvport=DEFAULT_UDP, recvip=DEFAULT_GW): ''' Instantiates the KillerBee class for the Sewio Sniffer. @type dev: String @param dev: IP address (ex 10.10.10.2) @type recvport: Integer @param recvport: UDP port to listen for sniffed packets on. @type recvip: String @param recvip: IP address of the host, where the sniffer will send sniffed packets to. @return: None @rtype: None ''' self._channel = None self._modulation = 0 #unknown, will be set by change channel currently self.handle = None self.dev = dev #TODO The receive port and receive IP address are currently not # obtained from or verified against the Sewio sniffer, nor are they # used to change the settings on the sniffer. self.udp_recv_port = recvport self.udp_recv_ip = recvip self.__revision_num = getFirmwareVersion(self.dev) if self.__revision_num not in TESTED_FW_VERS: print("Warning: Firmware revision {0} reported by the sniffer is not currently supported. Errors may occur and dev_sewio.py may need updating.".format(self.__revision_num)) self.handle = socket.socket(AF_INET, SOCK_DGRAM) self.handle.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) self.handle.bind((self.udp_recv_ip, self.udp_recv_port)) self.__stream_open = False self.capabilities = KBCapabilities() self.__set_capabilities() self.sniffer = OpenSniffer('10.10.10.2')
def make_sock(port): sock = socket.socket(AF_INET, SOCK_DGRAM) sock.bind(('', port)) # bind to all interfaces/addresses by default return sock
def get_current_ip(): import socket ip = (([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0] return ip
def prepare_net_socket(self, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return self.prepare_socket(sock, port)
def __init__( self, address): self.sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(address)
def cmd_shutdown(): global is_exiting, cmd_socket, cmd is_exiting.set(); cmd_socket.close() socket.socket(AF_INET, SOCK_STREAM).connect((HOST, SOCKET_PORT)) cmd.join()
CloseHandle.argtypes = (HANDLE,) CloseHandle.restype = BOOL # Python API pythonapi.PyBuffer_New.argtypes = (c_ulong,) pythonapi.PyBuffer_New.restype = py_object pythonapi.PyErr_SetFromErrno.argtypes = (py_object,) pythonapi.PyErr_SetFromErrno.restype = py_object # ---------------------------------------------------------------------------- if __name__ == "__main__": import socket s = socket.socket() s.connect(("192.168.1.13",1)) prot_info = WSAPROTOCOL_INFO() prot_info_len = c_int(sizeof(prot_info)) getsockopt(s.fileno(), SOL_SOCKET, SO_PROTOCOL_INFOA, cast(byref(prot_info), c_char_p), byref(prot_info_len)) hints = addrinfo() hints.ai_family = prot_info.iAddressFamily; hints.ai_socktype = prot_info.iSocketType; hints.ai_protocol = prot_info.iProtocol; result = POINTER(addrinfo)() getaddrinfo("localhost", "5523", byref(hints), byref(result)); print result.contents.ai_family
def __openTCPProcotol(self): TCPSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPSock.bind((self.host,self.port)) return TCPSock