def Pack_tcp_packet(ip_src,port_src,ip_dst,port_dst,mac_src,mac_dst,flags,**kwargs): tcp = TCP.TCP(ip_src,port_src,ip_dst,port_dst,"") if "urg" in flags: tcp.set_urg() if "ack" in flags: tcp.set_ack() if "psh" in flags: tcp.set_psh() if "rst" in flags: tcp.set_rst() if "syn" in flags: tcp.set_syn() if "fin" in flags: tcp.set_fin() if "acknowledgment_number" in kwargs: tcp.acknowledgment_number = kwargs["acknowledgment_number"] if "sequence_number" in kwargs: tcp.sequence_number = kwargs["sequence_number"] if "payload" in kwargs: tcp.payload= kwargs["payload"] tcp_header = tcp.Pack() ip = IP.IP(ip_src,ip_dst,tcp_header) ip_header = ip.Pack() mac_src = Convert_mac_address(mac_src) mac_dst = Convert_mac_address(mac_dst) ethernet = Ethernet.Ethernet(mac_src,mac_dst,0x0800,ip_header) packet = ethernet.Pack() return packet,tcp.sequence_number
def register_to_persistence(self): s = socket.socket() # Create a socket object #host = '172.17.23.17' # just to show to bibhas sir----- ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() #self.ip = my_ip host = my_ip #--------------------------------- #host = '172.26.35.147' port = 9935 # Reserve a port for your service. s.connect((host, port)) message = " 1:JOIN server" # message format to join #message = raw_input() # get message as input from terminal s.send(message) msg = s.recv(1024) self.nodeid = msg[:msg.rfind(':') - 1] self.A_server = msg[msg.rfind(':') + 1:] print msg s.close() print('connection closed')
def __init__(self, master_port) : self.MASTER_PORT= int(master_port) # this is the port where client(3rd tier) and server(2nd tier) will listen #self.PORT_Mapper = port_mapper.PortMap() self.ip = "" connection_type = 1 print "GOING TO INITIALIZE IP ADDRESS" while True : try : if connection_type == 1 : self.ip = ni.ifaddresses('enp1s0')[2][0]['addr'] else : self.ip = ni.ifaddresses('eth0')[2][0]['addr'] if self.ip == "" : continue except : self.ip = ni.ifaddresses('eth0')[2][0]['addr'] finally : break ip_ob = IP.IP() # Get the ip of the system (machine_ip for master) my_ip = ip_ob.get_my_ip() self.ip = my_ip self.socket_obj = {} self.HOST = self.ip print "Initiating master ",my_ip self.master_node = master_8.Master(self.MASTER_PORT) # creating the master using file master_8.py
def UnPack_tcp_packet(packet): tcp = None try: ethernet = Ethernet.Ethernet("","","","") ethernet_payload = ethernet.UnPack(packet) ip = IP.IP("","","") ip.UnPack(ethernet.Ethernet_payload) tcp = TCP.TCP("","","","","") tcp.UnPack(ip.payload) except Exception,e: return None
def __init__(self, local_address, remote_address=None, server_isn=None, client_isn=None, sample_RTT=None): self.__sent_but_not_acked = [ ] # a list of tuple, in the order of sending order. Each tuple contain a wanting ack number and data(NOT TCP OBJECT) self.__sample_RTT_to_record = { } # a dict, the key of which is the wanting ack number, the value of which is the start_time (or None, indicating this message won’t count to sample_RTT). self.__sample_RTT = sample_RTT # double self.__estimated_RTT = sample_RTT # double self.__dev_RTT = 0 # double self.__window_buffer = [ ] # a list of tuples, a tuple is in the format of (sequence_number, data) self.__received_buffer = b'' # bytes, used to store complete infomation, which is also in order. self.__ack_to_be_sent = [] self.__window_size = 5000 self.__segment_size = 500 self.__local_address = local_address self.__is_time_out = False # init is_timeout self.__send_buffer = b'' self.__time_out = 0 # todo init timeout self.__timer = threading.Thread() self.__timer_pid = 0 # helper variable for timer self.__duplicate_ack = 0 # init duplicate ack number local_ip = local_address[0] if server_isn: # if the socket is build by server # pass sequence number and last_acked_number self.__next_sequence_number = server_isn self.__last_ack_received = server_isn # SendBase self.__last_acked_sent = client_isn # init remote address and set up ip layer self.__remote_address = remote_address self.__ip = IP.IP(IP.PROTOCOL_TCP, self.__local_address[0], self.__remote_address[0]) # start sending process self.__sending_process = threading.Thread( target=self._sending_thread) self.__sending_process.start() self.__time_out = self._get_new_timeout() else: self.__next_sequence_number = random.randint(0, 2147483645)
def __init__(self, id, name="Default", online=False, adress=IP(name="127.0.0.0")): self.id = id PeerList[adress.name] = self DNSList[name] = adress self.name = name self.online = online self.sockets = {} self.receivedPackets = {} #Paquets reçus, archivés self.pendingData = [ ] #Paquets à envoyer, en attente, fournis par le client local self.contacts = { } #Tableau correspondance IP-socket pour ce peer (self) self.IPadress = adress self.availableSockets = [] self.start()
def listen(self, backlog=None): """ listen([backlog]) Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen. """ if not self.__local_address: raise AddressNotSpecified("Did you bind address for this socket?") if self.__local_address[1] in buffer_list.keys(): raise PortAlreadyInUse("Port is already in use.") # print('start listening') # open buffer for listening buffer_list['listening'][self.__local_address[1]] = {'queue': []} # print('create buffer_list') # print(buffer_list) # set up ip layer self.__ip = IP.IP(IP.PROTOCOL_TCP, self.__local_address[0])
def get_masters_from_persistence(message): s = socket.socket() # Create a socket object #host = '172.17.23.17' #host = '172.26.35.147' # just to show to bibhas sir----- ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() #self.ip = my_ip host = my_ip #--------------------------------- port = 9935 # Reserve a port for your service. s.connect((host, port)) print "connected server to persis to get master" s.send(message) print "hey 000" masters_list = s.recv(1024) #print "heuu ",masters_list s.close() print('connection closed') return masters_list
def main(): ## Define Variables ### totalbytes = 0 timestamp = time.time() totaltime = 0 totalrcvs = 0 INETX = False ## Find the current Host of the Analyzer ### operating_system = platform.system() HOST = socket.gethostbyname(socket.gethostname()) ## Windows and Linux(Raspberry Pi) Bind differently to a Socket ### if operating_system == 'Windows': conn = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) conn.bind((HOST, 0)) conn.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) conn.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) else: conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) conn.bind(('eth0', 0)) ## while True: if operating_system == 'Linux': raw_data, addr = conn.recvfrom(65535) ethernet_header = ethernet.Ethernet() ethernet_header.unpack(raw_data) ##socket for windows skips the Ethernet layer as this is not a requirement. ### if ethernet_header.eth_proto == 8 or operating_system == 'Windows': ip_header = ip.IP() ip_header.unpack(raw_data[14:]) if ip_header.protocol == 17 and ip_header.src_ip != '192.168.28.10': udp_header = udp.UDP() udp_header.unpack(raw_data[34:]) donestamp = time.time() data = len(raw_data) totalbytes += data totalrcvs += 1 totaltime = round((donestamp - timestamp), 0) rate = round( (((totalbytes * 8) / (donestamp - timestamp)) / 1000), 3) if hexConvert(udp_header.control) == '11000000': INETX = True inetx_header = inetx.INETX() inetx_header.unpack(raw_data[42:]) elif hexConvert(udp_header.control) != '11000000': iena_header = iena.IENA() iena_header.unpack(raw_data[42:]) ## publish contents of headers to MQTT ## if INETX == True: INETXpacket = { 'type': 'INETX', 'id': hexConvert(inetx_header.streamid), 'seq': inetx_header.sequence, 'src': ipv4(ip_header.src_ip), 'dst': ipv4(ip_header.dst_ip), 'size': udp_header.len, 'time': ptp(inetx_header.ptptime), 'BR': inetx_header.bitRate(), } packet_json = json.dumps(INETXpacket) ttl = json.dumps({ 'ttlBR': rate, 'pktNo': totalrcvs, 'drop': inetx_header.missedcount, }) client.publish("Packet", packet_json) client.publish("ttl", ttl) else: IENApacket = { 'type': 'IENA', 'id': hexConvert(iena_header.key), 'seq': iena_header.sequence, 'src': ipv4(ip_header.src_ip), 'dst': ipv4(ip_header.dst_ip), 'size': udp_header.len, 'time': unix(iena_header.timeHi, iena_header.timeLo), 'BR': iena_header.bitRate(), } packet_json = json.dumps(IENApacket) ttl = json.dumps({ 'ttlBR': rate, 'pktNo': totalrcvs, 'drop': iena_header.missedcount, }) client.publish("Packet", packet_json) client.publish("ttl", ttl)
def client_thread(buff): global BUFFER, count count += 1 ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() #self.ip = my_ip #--------------------------------- my_ip = master_ip1 # ip of master conn = buff[0] self = buff[1] used_port = 0 file_server = "" #infinite loop so that function do not terminate and thread do not end. #here should be added a try catch block - to detect lost connecions or failed connections try : while True: '''here there will be the logic * to respond to interconnection request from another tier2 server (this will be constant connections) * the other type of connection may be from clients.. this can be search request, * each client will be connected to the client * each upload or download will be done by server initiating a new connection from and to client respectively ''' #Receiving from client data = conn.recv(BUFFER) print "data ",data print data[:-1] #reply = 'OK...' + data # '7:' prefix for connection ... corresponding reply # '9:' search request .. # inverted trie implementation # '15:' upload request from client if data[:-1] == '' : break elif data[:2] == '7:' : print 'New connection initiated; sending reply' message = '8:ACK' while True: try : #Set the whole string conn.sendall(message) except socket.error: #Send failed print 'Send failed and retrying' continue finally : break elif data[:3] == '14:' : print 'Threaded implementation of file upload' used_port = self.PORT_Mapper.get_port() print "Get port = %d" %used_port self.PORT_Mapper.use_port(used_port) message = '15:port:' + str(used_port) file_server = FileServer.FileServer(used_port) file_server.setSharedDirectory(files_path) file_server.startServer() print "sending to client : ",message while True: try : conn.sendall(message) except socket.error: print 'Send failed and retrying' break finally : break #break elif data[:3] == '16:' : #Threaded implementation of file upload print 'updation of trie after file upload' self.PORT_Mapper.free_port(used_port) message = '17:ACK:' + str("none") file_server.stopServer() filename_key = data[data.rfind(':')+1:] print "filename_key",filename_key #update_trie(self, filename) masters_list = get_masters_from_persistence("server 2:LIST_OF_MASTERS") list_of_masters = masters_list.split() print "list of masters :" , list_of_masters,"PPPPPPPPP" for master_ip in list_of_masters: update_trie(self, filename_key, master_ip) # later not to store ip beacuse trie on master will just have the file names #tester(self,"666666") print "Updated trie in all masters" while True: try : #Set the whole string conn.sendall(message) except socket.error: #Send failed print 'Send failed and retrying' continue finally : count -= 1 conn.close() break #elif data[:3] == '10:' : # print 'Threaded implementation of file upload' # message = '11:IP_address:10.0.0.4' # while True: # try : # #Set the whole string # conn.sendall(message) # except socket.error: # #Send failed # print 'Send failed and retrying' # continue # finally : # break elif data[:3] == '22:' : print "Pastry search protocol" filekey = data[data.rfind(':')+1:] print "filekey :",filekey step = 0 for i in range(0,min(len(self.nodeid),filekey)): if(self.nodeid[i] != filekey[i]): break else: step += 1 print "current matching steps :",step target_ip = client_back_process(self,conn,filekey,str(step)) return target_ip elif data[:-1] == 'exit': print 'connection closed' conn.close() break #conn.sendall(reply) except : conn.close() finally : conn.close()
def start_listening(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() ip_ob = IP.IP() # Get the ip of the system (machine_ip for persistence) my_ip = ip_ob.get_my_ip() s.bind((my_ip, curr_port)) # select a port for binding s.listen(10) print "Ip of persistence is : ", my_ip stor = Storage() # database will be created only once print "Creating dummy table" #---------Dummy Table--------- '''stor.add_new_server('10.0.0.9') server_id = hashlib.sha1('10.0.0.9').hexdigest() stor.add_id_server('10.0.0.9',server_id) #stor.add_load_server('172.31.1.1',4) stor.add_new_server('10.0.0.5') server_id = hashlib.sha1('10.0.0.5').hexdigest() stor.add_id_server('10.0.0.5',server_id) #stor.add_load_server('172.31.1.2',2) stor.add_new_server('10.0.0.7') server_id = hashlib.sha1('10.0.0.7').hexdigest() stor.add_id_server('10.0.0.7',server_id) #stor.add_load_server('172.31.1.3',8) stor.add_new_server('10.0.0.8') server_id = hashlib.sha1('10.0.0.8').hexdigest() stor.add_id_server('10.0.0.8',server_id) #stor.add_load_server('172.31.1.4',1) stor.add_new_server('10.0.0.1') server_id = hashlib.sha1('10.0.0.1').hexdigest() stor.add_id_server('10.0.0.1',server_id) #stor.add_load_server('172.31.1.5',3) stor.add_new_server('10.0.0.4') server_id = hashlib.sha1('10.0.0.4').hexdigest() stor.add_id_server('10.0.0.4',server_id) #stor.add_load_server('172.31.1.6',4) stor.add_new_server('10.0.0.3') server_id = hashlib.sha1('10.0.0.3').hexdigest() stor.add_id_server('10.0.0.3',server_id) #stor.add_load_server('172.31.1.7',4) ''' while True: conn, addr = s.accept() msg = conn.recv(1024) print msg new_ip = addr[ 0] # ip from the addr recieved after connection of master/server if msg.find("master") is not -1: if msg.find('1:JOIN') is not -1: try: A_server = stor.get_first_server(new_ip) stor.add_new_master(new_ip) # new server added master_id = hashlib.sha1(new_ip).hexdigest() stor.add_id_master(new_ip, master_id) #adding id for the master conn.send(master_id + ":" + A_server) except: print 'Error occured' conn.send('Master addition FAILED') elif msg.find('2:HBEAT') is not -1: try: stor.add_heartbeat_master( new_ip ) # updating the time when last ping came from the masters/servers conn.send('Master Hbeat UPDATED') except: print 'Error occured' conn.send('Master hbeat update FAILED') pass elif msg.find("server") is not -1: if msg.find('1:JOIN') is not -1: try: status = stor.if_first_server() # new server added if (str(status) is "0"): print "Adding the first server" else: status = stor.get_first_server(new_ip) stor.add_new_server(new_ip) # new server added status = str(status) server_id = hashlib.sha1( new_ip).hexdigest() # nodeis from the server ip #server_id = str(server_id) server_id = stor.add_id_server( new_ip, server_id) #adding id for the server conn.send(server_id + ":" + status) # sending the nodeid to the server except: print 'Error occured' conn.send('Peer addition FAILED') elif msg.find('2:HBEAT') is not -1: try: stor.add_heartbeat_server( new_ip ) # updating the time when last ping came from the masters/servers conn.send('Peer hbeat UPDATED') except: print 'Error occured' conn.send('Peer Hbeat updation FAILED') elif msg.find('IP_FROM_ID') is not -1: id = msg[msg.rfind(':') + 1:] try: # print str(id) ip = stor.get_ip_from_nodeid( str(id) ) # updating the time when last ping came from the masters/servers #print "ippppp ",ip conn.send(str(ip)) except: print 'Error occured' conn.send('return of ip FAILED') elif msg.find('2:LIST_OF_MASTERS') is not -1: try: lis = stor.get_list_of_masters( ) # updating the time when last ping came from the masters/servers conn.send(lis) except: print 'Error occured' conn.send('list of masters sending FAILED') pass elif msg.find("client") is not -1: print "client detected" if msg.find('1:MASTER') is not -1: try: master_ip = stor.get_master() conn.send('Master ip:' + master_ip) except: print 'Error occured master ip' conn.send('Master allocation failed') elif msg.find('K-NEAREST') is not -1: filekey = msg[msg.rfind(':') + 1:] #recieved client_ip from the server try: server_ip = stor.get_k_nearest_server(filekey) conn.send(server_ip) except: print 'Error occured k nearest failed' conn.send('K nearest allocation failed') elif msg.find('2:SERVER1' ) is not -1: # to get the server with least load try: server_ip = stor.get_server() conn.send(server_ip) except: print 'Error : get server failed' conn.send('get server failed') elif msg.find('2:SERVER2') is not -1: try: server_ip = stor.get_server() key = stor.get_filekey() conn.send(server_ip + ":" + key) except: print 'server allocation failed' conn.send('get filekey allocation failed') pass
def __init__(self, server_port, peer_forward_port, peer_backward_port, master_port) : #create id of server using the hash of IP address and MAC self.HOST = '' # Symbolic name meaning all available interfaces #self.PORT = 9167 # All servers will listen on this port -- to listen to CLIENTS #self.PEER_PORT = 9570 # to listen to PEERS #self.MASTER_PORT = 11500 self.PORT = int(server_port) self.PEER_HOST = "10.0.0.4" self.PEER_FORWARD_PORT = int(peer_forward_port) self.PEER_BACKWARD_PORT = int(peer_backward_port) self.MASTER_PORT= int(master_port) self.MASTER_HOST = "10.0.0.4" self.PORT_Mapper = port_mapper.PortMap() self.ip = "" # Pastry protocol datastructures :-------- self.leaf = [] # contain Leaf nodes having L/2 closest small and L/2 closest greater nodes self.neighbour = [] # contain neighbours - k closest nodes according to the proximity measure self.routing = [] # routing table connection_type = 1 print "GOING TO INITIALIZE IP ADDRESSSSSSSS" while True : try : if connection_type == 1 : self.ip = ni.ifaddresses('enp1s0')[2][0]['addr'] else : self.ip = ni.ifaddresses('eth0')[2][0]['addr'] if self.ip == "" : continue except : self.ip = ni.ifaddresses('eth0')[2][0]['addr'] finally : break self.socket_obj = {} # just to show to bibhas sir----- ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() self.ip = my_ip #--------------------------------- self.HOST = self.ip fHandle = open('master_stub.txt') # write 0 in stub file when starting the network data = fHandle.read() fHandle.close() data = data.strip() #print "getting list of masters :" #masters_list = get_masters_from_persistence("server 2:LIST_OF_MASTERS") #print "99 ",masters_list #exit() # if data == '0' : # decide this condition of master selection later # print "Initiating master" # self.master_node = master_8.Master(self.MASTER_PORT) # else : print "Initiating Server" #self.register_to_persistence() ### to get ip of A server from persistence A_server = try: data = Thread(target=self.peer_front_process, args=("REQUEST <ip>" +self.ip + " :0",A_server)).start() # Separate thread to accept the incoming connections from tier 2 peers except Exception, errtxt: print errtxt
def client_thread(buff): global BUFFER, count count += 1 # just to show to bibhas sir----- ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() #self.ip = my_ip #--------------------------------- #my_ip = "10.0.0.4" # ip of master conn = buff[0] self = buff[1] used_port = 0 file_server = "" #infinite loop so that function do not terminate and thread do not end. #here should be added a try catch block - to detect lost connecions or failed connections try : while True: '''here there will be the logic * to respond to interconnection request from another tier2 server (this will be constant connections) * the other type of connection may be from clients.. this can be search request, * each client will be connected to the client * each upload or download will be done by server initiating a new connection from and to client respectively ''' #Receiving from client data = conn.recv(BUFFER) print "data ",data print data[:-1] reply = 'OK...' + data # '7:' prefix for connection ... corresponding reply # '9:' search request .. # inverted trie implementation # '15:' upload request from client if data[:-1] == '' : break elif data[:2] == '7:' : print 'New connection initiated; sending reply' message = '8:ACK' while True: try : #Set the whole string conn.sendall(message) except socket.error: #Send failed print 'Send failed and retrying' continue finally : break elif data[:3] == '14:' : print 'Threaded implementation of file upload' used_port = self.PORT_Mapper.get_port() print "Get port = %d" %used_port self.PORT_Mapper.use_port(used_port) message = '15:port:' + str(used_port) file_server = FileServer.FileServer(used_port) file_server.setSharedDirectory('/home/kritika/Desktop/files') file_server.startServer() while True: try : conn.sendall(message) except socket.error: print 'Send failed and retrying' break finally : break #break elif data[:3] == '16:' : #Threaded implementation of file upload print 'updation of trie after file upload' self.PORT_Mapper.free_port(used_port) message = '17:ACK:' + str("none") file_server.stopServer() filename = data[data.rfind(':')+1:] #update_trie(self, filename) masters_list = get_masters_from_persistence("server 2:LIST_OF_MASTERS") list_of_masters = masters_list.split() for master_ip in list_of_masters: update_trie(self, filename+'<IP>'+my_ip,master_ip) # later not to store ip beacuse trie on master will just have the file names while True: try : #Set the whole string conn.sendall(message) except socket.error: #Send failed print 'Send failed and retrying' continue finally : count -= 1 conn.close() break #elif data[:3] == '10:' : # print 'Threaded implementation of file upload' # message = '11:IP_address:10.0.0.4' # while True: # try : # #Set the whole string # conn.sendall(message) # except socket.error: # #Send failed # print 'Send failed and retrying' # continue # finally : # break elif data[:-1] == 'exit': print 'connection closed' conn.close() break #conn.sendall(reply) except : conn.close() finally : conn.close()
# This file is part of openWNS (open Wireless Network Simulator) # _____________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 5, D-52074 Aachen, Germany # phone: ++49-241-80-27910, # fax: ++49-241-80-22242 # email: [email protected] # www: http://www.openwns.org # _____________________________________________________________________________ # # openWNS is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License version 2 as published by the # Free Software Foundation; # # openWNS is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### import openwns import IP openwns.simulator.OpenWNS.modules.ip = IP.IP()
def onQQMessage(bot, contact, member, content): try: if len(content) == 0 or content[0] != '-' or bot.isMe(contact, member): return if content == '-5': bot.SendTo(contact, getChaos.getScb_555()) elif content == '-3': bot.SendTo(contact, '暂不支持三阶打乱') elif content == '-2': bot.SendTo(contact, '二阶打乱仅支持旧标准(随机打乱)') bot.SendTo(contact, getChaos.getPsbScb_222()) if '-wca' in content: flag, thing = Bot.procMsg(content) if flag == 0: bot.SendTo(contact, '有什么能帮到您的么?') elif flag == 1: personList = Spider.spider_main(thing) if len(personList) == 0: bot.SendTo(contact, '找不到这枚外星人。。。') elif len(personList) == 1: for person in personList: sendStr = '' sendStr += str( person[0]) + '\n' + str(person[1] + '\n') for item in person[3].keys(): sendStr += str(item) + ' ' + str( person[3][item][0] + '|' + str(person[3][item][1]) + '\n') bot.SendTo(contact, sendStr) elif len(personList) >= 2: sendStr = '' sendStr += str(len(personList)) + ' items\n' if len(personList) > 4: for i in range(4): sendStr += str(i + 1) + '. ' + str( personList[i][0]) + ' ' + str( personList[i][1]) + '\n' sendStr += '......' else: for i in range(len(personList)): sendStr += str(i + 1) + '. ' + str( personList[i][0]) + ' ' + str( personList[i][1]) + '\n' bot.SendTo(contact, sendStr) if '[@ME]' in content: bot.SendTo(contact, '拒绝被撩') if '-ip' in content: tlist = content.split('-ip') ip = tlist[1] sendStr = '' sendStr += str(ip) t = IP.IP(ip) sendStr += t.get_phy() bot.SendTo(contact, sendStr) if '-phone' in content: sendStr = '' sendStr += '手机归属地查询正在开发中.....' bot.SendTo(contact, sendStr) if '-post' in content: sendStr = '' sendStr += '城市邮编查询正在开发中......' bot.SendTo(contact, sendStr) except: bot.SendTo('SNU 各位大佬的小', 'Bot又炸了')
def push(data, remote_ip): # print # print('[static method]received data from ip, it\'s from', remote_ip) tcp = TCP() tcp.from_bytes(data) # print('current buffer_list is') # print(buffer_list) # print('src_port is', tcp.src_port, end=' ') # print('dst_port is', tcp.dst_port, end=' ') # print('content is', str(tcp)) # print() # print basic info # names = ['CWR','ECE','URG','ACK','PSH','RST','SYN','FIN'] # byte = tcp.flag_bits # byte = bin(int.from_bytes(byte, 'little'))[2:] # print(bytes) # for i in range(8): # print("{}:{}".format(names[i], byte[i])) # # if tcp.SYN == 1 and tcp.ACK != 1: # b remote_address = (remote_ip, tcp.src_port) if tcp.RST: raise ConnectionResetError try: if tcp.SYN == 1 and tcp.ACK == 1: print('detect second handshake') try: buffer_list['connecting'][remote_address].append(data) except: server_isn = tcp.sequence_number client_isn = tcp.acknowledgement_number remote_port = tcp.src_port local_port = tcp.dst_port tcp = TCP() tcp.sequence_number = client_isn tcp.acknowledgement_number = server_isn tcp.src_port = local_port tcp.dst_port = remote_port tmp_ip = IP.IP(protocol=IP.PROTOCOL_TCP, src_ip=local_ip, dst_ip=remote_ip) print('retransmitted', tcp.sequence_number, tcp.acknowledge_number) print("str", str(tcp)) tmp_ip.send(bytes(tcp)) elif tcp.SYN == 1: # it's first handshake print('detect first handshake') buffer_list['listening'][tcp.dst_port]['queue'].append( (data, remote_address)) else: # it's not first handshake # self.__last_acked_number = tcp.acknowledgement_number # todo update last_acked_number # check whether it's a third handshake if remote_address in buffer_list['connected']['objects'].keys( ): print('detect normal message') # it's not a third handshake # buffer_list['connected'][remote_address].append((data, remote_address)) # get tcp object obj = buffer_list['connected']['objects'][remote_address] # let obj add data obj._add_data(data) else: # it's a third handshake print('detect third handshake') buffer_list['connecting'][remote_address].append( (data, remote_address)) except: local_port = tcp.dst_port remote_port = tcp.src_port sequence_number = tcp.acknowledgement_number acknowledge_number = tcp.sequence_number tcp = TCP() tcp.RST = 1 tcp.ACK = 0 tcp.src_port = local_port tcp.dst_port = remote_port tcp.sequence_number = sequence_number tcp.acknowledgement_number = acknowledge_number tmp_ip = IP.IP(protocol=IP.PROTOCOL_TCP, src_ip=local_ip, dst_ip=remote_ip) tmp_ip.send(bytes(tcp))
def analyses_toute_les_trames(Liste_trames, fichier): """list [ tuple(list[octects], bool, int ,int) ] -> None Analyse toutes les trames recuperees """ length = len(Liste_trames) # nombre de trames recuperees # Parcours de toutes les trames recuperees for i in range(length): Trame, ok, ligne_erreur, taille = Liste_trames[i] print("\n********************* Analyse de la trame", i + 1, "******************** \n") # if la trame est errone en raison des offsets invalides if Trame == []: print( " \nLa trame", i, "est erronee car l'offset n'est pas dans l'ordre croissant\n") fichier.write("*\n!\n") continue # if il manque des octets dans la trame if not ok: print(" \nLa trame", i, "a rencontré une erreur à la ligne ", ligne_erreur, " de sa trame\n") fichier.write("*\n!\n") continue print(taille, " octets de donnees") # donne des noms differents a chaque trame et leurs composantes str_num = str(i) str_Ethernet = "Ethernet_" + str_num str_IP = "IP_" + str_num str_TCP = "TCP_" + str_num str_HTTP = "HTTP_" + str_num # Entete Ethernet dest_mac = Trame[:6] # Destination (Adresse MAC) src_mac = Trame[6:12] # Soruce (Adresse MAC) type_ethernet = Trame[12:14] # Type Ethernet str_Ethernet = Ethernet(dest_mac, src_mac, type_ethernet) str_Ethernet.affichage() str_Ethernet.affichage_bouton(fichier) # If la trame n'est pas IPv4 then aller à la trame suivante if not est_IPv4(Trame): print("Notre analyseur ne prend pas en compte le protocole 0x" + ''.join(Trame[12:14])) fichier.write("14 " + str(taille)) continue # Entete IPv4 version = Trame[14][0] # Version header_length_ip = Trame[14][1] # Header Length dsf = Trame[15] # Differentiated Sevices Field total_length = Trame[16:18] # Total Length id = Trame[18:20] # Identification flags_ip = Trame[20] # Flags offset = Trame[20:22] # Framgment offset ttl = Trame[22] # Time to live protocol = Trame[23] # Protocol checksum_ip = Trame[24:26] # Header Checksum src_ip = Trame[26:30] # Source IP dest_ip = Trame[30:34] # Destination IP options_ip = [] # Options IP str_IP = IP(version, header_length_ip, dsf, total_length, id, flags_ip, offset, ttl, protocol, checksum_ip, src_ip, dest_ip, options_ip) taille_options_IP = str_IP.taille_options_IP( ) # Recupere la taille des options IP si elles existent fin_IP = 34 + taille_options_IP # Recupere le dernier octect de l'entete IP str_IP.set_options(Trame[34:fin_IP]) # Affectation des options de IP str_IP.verification_checksum(Trame[14:fin_IP]) # Check le checksum str_IP.affichage() str_IP.affichage_bouton(fichier) # if la trame recuperee n'est pas de la taille de totale_length if not nombre_octects_exacts(taille, int(''.join(str_IP.total_length), 16)): print("La trame contient ", taille, "octets alors qu'elle devrait en contenir", int(''.join(str_IP.total_length), 16) + 14) continue # if la trame n'est pas TCP then aller à la trame suivante if not est_TCP(Trame): print("\nNotre analyseur ne prend pas en compte le protocole 0x" + ''.join(Trame[23])) fichier.write(str(fin_IP) + " " + str(taille) + "\n") continue # Entete TCP debut_TCP = fin_IP # premier octer du segment TCP src_port = Trame[debut_TCP:debut_TCP + 2] # Source Port dest_port = Trame[debut_TCP + 2:debut_TCP + 4] # Destination Port sequence = Trame[debut_TCP + 4:debut_TCP + 8] # Sequence number acknowledgment = Trame[debut_TCP + 8:debut_TCP + 12] # acknowledgment number header_length_tcp = Trame[debut_TCP + 12] # Header Length flags_tcp = Trame[debut_TCP + 12:debut_TCP + 14] # Flags window = Trame[debut_TCP + 14:debut_TCP + 16] # Window checksum_tcp = Trame[debut_TCP + 16:debut_TCP + 18] # Checksum urgent_pointer = Trame[debut_TCP + 18:debut_TCP + 20] # Urgent pointer options_tcp = [] # Options TCP_length = str( hex( int(''.join(str_IP.total_length), 16) - 20 - taille_options_IP)[2:].zfill(4)) # Taille du segment TCP str_TCP = TCP(src_port, dest_port, sequence, acknowledgment, header_length_tcp, flags_tcp, window, checksum_tcp, urgent_pointer, options_tcp) str_TCP.set_options(Trame[debut_TCP + 20:debut_TCP + 20 + str_TCP.taille_options_TCP()]) str_TCP.verification_checksum(src_ip + dest_ip + ["00"] + [protocol] + [TCP_length[0:2]] + [TCP_length[2:4]] + Trame[debut_TCP:]) # Check le checksum str_TCP.affichage() str_TCP.affichage_bouton(fichier, debut_TCP) taille_options_TCP = str_TCP.taille_options_TCP( ) # Recupère la taille des options TCP si elles existent fin_TCP = debut_TCP + 20 + taille_options_TCP # Recupere le dernier octect de l'entete IP # if pas de data then aller a la trame suivante if fin_TCP == taille: continue # if la trame n'est pas HTTP then aller à la trame suivante if not est_HTTP(Trame, src_port, dest_port): print( "\nNotre analyseur ne peut pas lire le contenu de ce segment (pas HTTP)" ) continue debut_HTTP = fin_TCP # Récupère le premier octet du segment HTTP str_HTTP = HTTP(Trame[debut_HTTP:]) str_HTTP.affichage() str_HTTP.affichage_bouton(fichier, debut_HTTP) return None
def __init__(self, port): #create id of server using the hash of IP address and MAC self.HOST = '' # Symbolic name meaning all available interfaces self.PORT = int(port) self.tier_two_server_count = 0 self.ip = "" connection_type = 1 while True: try: if connection_type == 1: self.ip = ni.ifaddresses('enp1s0')[2][0]['addr'] else: self.ip = ni.ifaddresses('eth0')[2][0]['addr'] except: self.ip = ni.ifaddresses('eth0')[2][0]['addr'] finally: break # checking ^^^^ ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() self.ip = my_ip #--------------------------------- # variable for initial logic .. # master sends own ip print "MY MASTER IP ::::" + self.ip self.last_ip = self.ip self.HOST = self.ip #print "connecting to persistence in master" self.register_to_persistence() self.CONNECTION = { self.ip: 1 } # this has also to be implemented in a database self.CONNECTION_ID = { } # this has also to be implemented in the same database .. for the ID self.socket_objects = [] print "created trie object" self.Trie_obj = Trie.Trie() # dummy trie #print "creating Dummy trie:" #self.Trie_obj.insert("Animal<id>4343") #self.Trie_obj.insert("Animals<id>4352") #self.Trie_obj.insert("Anima<id>768") #self.Trie_obj.insert("Animl<id>998") #print self.Trie_obj.search_get_json("Ani") #bound = self.socket_bind() #.. there is a definite pattern to accept request #here a mutex has to be implemented #this file should be implemented using a database ... #since the server creating a master is in actually a master #so it must update the file .. i.e the database about its existence #fHandle = open('master_stub.txt', 'w') #data = fHandle.write(self.ip + ',' + str(self.PORT)) #print "hyy ",data #data = fHandle.write('0') #fHandle.close() print "yes.. bind.. retuen" try: Thread(target=self.bind_and_serve, args=()).start() except Exception, errtxt: print errtxt
# ## ##### ##### # # # # #### # # # # # # # # # # ##### # # ##### # # # # # # ## # # # # # # # # # # # # # # # # # # ## # # # # ### ### ## # # # #### # # ### ### # # # ### ### ## # ### # ''') print(''' #### # ## # # # # # # # ## ### #### ### ### ### # #### ## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ## ### ### ### ### ''') ip_ob = IP.IP() # Get the ip of the system (machine_ip for persistence) my_ip = ip_ob.get_my_ip() users = [] UserA = {'id': 'A' , 'name' : 'Alice','key':'Alice@123'} UserB = {'id': 'B' , 'name' : 'Bob','key':'Bob@123'} UserC = {'id': 'C' , 'name' : 'Cherry','key':'Cherry@123'} users.append(UserA) users.append(UserB) users.append(UserC) def client_thread(buff): global BUFFER, count conn = buff[0] msg = conn.recv(1024)
def __init__(self): ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() self.MASTER_SERVER_IP = my_ip # put ip of master server here manually self.MASTER_SERVER_PORT = mast_port self.TIER_TWO_SERVER_PORT = serv_port # first port put in case of running of server.py
def bind(self, address): self.src_ip = address[0] self.src_port = address[1] self.IP = IP.IP(IP.PROTOCOL_UDP, self.src_ip) UDP.buffer[self.src_port] = queue.Queue()
def send(src_ip, dst_ip, icmp): Network = IP.IP(IP.PROTOCOL_ICMP, src_ip, dst_ip) Network.send(icmp.pack())
else: rev = 0 ipaddr = sys.argv[1] if nb_arg == 3 else ERROR_IP_ARG rev_opt = sys.argv[2] if nb_arg == 3 else ERROR_OPT_ARG_1 if (rev_opt != "-rev"): print("Erreur: argument non reconnu (", rev_opt, ")") print("Commande:", sys.argv[0], "<adresse IP> [-rev] OU ", sys.argv[0], "<nom du fichier>") sys.exit(1) else: rev = 1 try: IP(ipaddr) except Exception as e: print("Erreur: adresse IP invalide") raise e try: img = os.popen("./connectPi.sh", ipaddr, rev, "", "r").read except Exception as e: print("Erreur: la photo n'a pas pu être prise et/ou récupérée") raise e # Functions def addHellEyes(img, roi, ex, ey, ew, eh): begone_eyes = cv2.imread('begoneThotEyes.png') roi_h, roi_w, roi_v = roi.shape
import IP import KS import E import CAL main_ks = KS.KS() main_ks.main_ks() #PC_key 하위 폴더에 있는 키들 세팅함. string1 = "ghdwpakss" main_ip = IP.IP() cryptogram = main_ip.IP_main(string1) #크립토그램, IP단계 암호문 print("cryptogram :", cryptogram) def device_two_for_cry(cryptogram): L = cryptogram[:(len(cryptogram) // 2)] R = cryptogram[(len(cryptogram) // 2):] res = [] res.append(L) res.append(R) return res cry_list = device_two_for_cry(cryptogram) R = cry_list[(len(cry_list) - 1)] #여기서 분할하고 함수로 넘기기 main_e = E.E() expanded_R = main_e.E_main(R) this_round = 1
def accept(self): """accept() -> address tuple, server_isn int Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port). """ # fd, addr = self._accept() # If our type has the SOCK_NONBLOCK flag, we shouldn't pass it onto the # new socket. We do not currently allow passing SOCK_NONBLOCK to # accept4, so the returned socket is always blocking. # type = self.type & ~globals().get("SOCK_NONBLOCK", 0) # sock = socket(self.family, type, self.proto, fileno=fd) # Issue #7995: if no default timeout is set and the listening # socket had a (non-zero) timeout, force the new socket in blocking # mode to override platform-specific socket flags inheritance. # if getdefaulttimeout() is None and self.gettimeout(): # sock.setblocking(True) # return address, server_isn # if not self.__address: # raise AddressNotSpecified("Did you bind address for this socket?") # wait until one connected while buffer_list['listening'][self.__local_address[1]]['queue'] == []: continue # retrive first handshake data, (remote_ip, remote_port) = buffer_list['listening'][ self.__local_address[1]]['queue'].pop() tcp = TCP() tcp.from_bytes(data) if not (tcp.SYN == 1 and tcp.ACK == 0): # print("wrong tcp package received, it's not the first handshake") return client_isn = tcp.sequence_number print('first handshake received') # reformat remote_address address = (remote_ip, tcp.src_port) # generate a inital server_isn server_isn = random.randint(0, 2147483645) # build a tcp with server_isn and client_isn + 1 tcp = TCP() tcp.build(type=tcp.SEND_SYNACK, src_port=self.__local_address[1], dst_port=address[1], sequence_number=server_isn, acknowledgement_number=client_isn + 1) # send the second handshake and register a place for handshake tmp_ip = IP.IP(IP.PROTOCOL_TCP, self.__local_address[0], remote_ip) tmp_ip.send(bytes(tcp)) buffer_list['connecting'][address] = [] print('second handshake sent, waiting for the third handshake') # record the first time of send package fisrt_pacakge_sent_time = time.time() # wait until third handshake appear send_send_start_time = time.time() flag_3 = True flag_6 = False flag_12 = False while buffer_list['connecting'][address] == []: if flag_3 and (time.time() - send_send_start_time >= 2): print('waiting second hand time out, wait another 6s') tmp_ip.send(bytes(tcp)) send_send_start_time = time.time() flag_3 = False flag_6 = True send_send_start_time = time.time() elif flag_6 and (time.time() - send_send_start_time >= 2): print('waiting second hand time out, wait another 12s') tmp_ip.send(bytes(tcp)) send_send_start_time = time.time() flag_6 = False flag_12 = True send_send_start_time = time.time() elif flag_12 and (time.time() - send_send_start_time >= 2): print('waiting second hand time out, wait another 24s') tmp_ip.send(bytes(tcp)) flag_6 = False flag_12 = False send_send_start_time = time.time() elif (time.time() - send_send_start_time >= 4): print('waiting second hand time out, wait another 6s') print('break') return continue # record the time of receiving second package self.__sample_RTT = time.time() - fisrt_pacakge_sent_time self.__estimated_RTT = self.__sample_RTT print('first sample RTT generated, it\'s {}'.format(self.__sample_RTT)) # retrive the third handshake data, address = buffer_list['connecting'][address].pop() tcp = TCP() tcp.from_bytes(data) print('third handshake retrived') # check third handshake if not (tcp.sequence_number == client_isn + 1 and tcp.acknowledgement_number == server_isn + 1): print( 'SYN {}, ACK{}, tcp.sequencenumber({}) ?= client_isn({}), tcp.acknowledgement_number({}) ?= server_isn({})' .format(tcp.SYN, tcp.ACK, tcp.sequence_number, client_isn + 1, tcp.acknowledgement_number, server_isn + 1)) print( "wrong tcp package received, it's not the correct third handshake" ) return # update server_isn server_isn += 1 # open a place for the newly connected socket buffer_list['connected'][address] = [] # delete the original space buffer_list['connecting'].pop(address) # add data to the buffer if any # buffer_list['connected'][address].append(tcp.data) # Build a new tcpSocket tcpSocket = TCPsocket(self.__local_address, address, server_isn, client_isn + 1, self.__sample_RTT) # put the conneceted object in buffer buffer_list['connected']['objects'][address] = tcpSocket # add data if any if tcp.data != b'': tcpSocket._add_data(tcp.data) print('done with accept, returned address and server_isn') return address, tcpSocket
from Socket import * from IP import * from Packet import * from Port import * from Peer import * A = Peer(0, name="A", online=True, adress=IP(name="125.365.245.158")) A.createSocket(1234) B = Peer(1, name="B", online=True, adress=IP(name="458.256.179.245")) B.createSocket(0) A.sendData("B", "Issouffle") B.sendData("A", "LOL") def arret(): A.thread.stop() B.thread.stop()
def connect( self, remote_address): # real signature unknown; restored from __doc__ """ connect(address) Connect the socket to a remote address. For IP sockets, the address is a pair (host, port). """ # init remote_address self.__remote_address = remote_address # connect to IP layer print('connecting to IP layer') self.__ip = IP.IP(IP.PROTOCOL_TCP, self.__local_address[0], dst_ip=remote_address[0]) print('connected to IP layer') # generate client_isn self.__isn = random.randint(0, 2147483645) client_isn = self.__isn print('generated isn', self.__isn) # build a tcp object with SYN tcp = TCP() tcp.build(type=tcp.SEND_SYN, src_port=self.__local_address[1], dst_port=remote_address[1], sequence_number=self.__isn) # sign a space in buffer_list buffer_list['connecting'][remote_address] = [] # sent tcp object self.__ip.send(bytes(tcp)) print('sent tcp object') # record first_package_sent_time first_package_sent_time = time.time() # wait for sencond hanshake print('waiting for sencond hanshake') star_time = time.time() flag_3 = True flag_6 = False flag_12 = False while buffer_list['connecting'][remote_address] == []: if flag_3 and time.time() - star_time >= 2: print('3s timeout') self.__ip.send(bytes(tcp)) flag_3 = False flag_6 = True star_time = time.time() elif flag_6 and time.time() - star_time >= 2: print('6s timeout') self.__ip.send(bytes(tcp)) flag_6 = False flag_12 = True star_time = time.time() elif flag_12 and time.time() - star_time >= 2: print('12s timeout') self.__ip.send(bytes(tcp)) flag_12 = False star_time = time.time() elif time.time() - star_time >= 4: print('break') return continue self.status = 'established' # record first_package_receive_time self.__sample_RTT = time.time() - first_package_sent_time self.__estimated_RTT = self.__sample_RTT self._get_new_timeout() print('fisrt sampleRTT inited, it\'s', self.__sample_RTT) # retrive data data = buffer_list['connecting'][remote_address].pop() print('retrived') # parse tcp object tcp = TCP() tcp.from_bytes(data) # check tcp object is right if not (tcp.SYN == 1 and tcp.ACK == 1 and tcp.acknowledgement_number == client_isn + 1): print('the tcp object is not right. Connect failed') return # if it's right, update server_isn, client_isn server_isn = tcp.sequence_number client_isn += 1 self.__next_sequence_number = client_isn print('client_isn sent', client_isn) self.__last_ack_received = tcp.acknowledgement_number # remove from buffer_list['connecting'], added to buffer_list['connected'] buffer_list['connecting'].pop(remote_address) buffer_list['connected']['objects'][remote_address] = self # generate last_ack_sent and update ack_to_be_sent list, last_ack_received self.__last_acked_sent = server_isn + 1 self.__ack_to_be_sent.append(self.__last_acked_sent) # start sending thread self.__sending_process = threading.Thread(target=self._sending_thread) self.__sending_process.start() print('connected')
import socket # Import socket module import IP # module to calculate system IP s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 11112 # Reserve a port for your service. s.connect((host, port)) ip_obj = IP.IP() # object for IP class my_ip = ip_obj.get_my_ip() #message = " 1:JOIN 1:" + my_ip # message format to join message = raw_input() # get message as input from terminal s.send(message) print s.recv(1024) s.close() print('connection closed')
#!/usr/bin/python import sys srom scapy.all import send, IP, ICMP if len(sys.argv) < 3: print sys.argv[0] + " <src_ip> <dst_ip>" sys.exit(1) packet = IP(src=sys.argv[1], dst=sys.argv[2]) / ICMP() answer = send(packet) if answer: answer.show()
from IP import * if __name__ == "__main__": #Example test case with generic IPv4 address and subnet mask specified. ipv4 = IP("192.168.1.1 255.255.255.0") print(ipv4) #IPv4 address using CIDR notation cidrNotation = IP("192.168.1.2 /24") print(cidrNotation) print("Network:", network(cidrNotation)) print("Broadcast:", broadcast(cidrNotation)) print("Host range:", hostRange(cidrNotation)) print("hostsAvailable:", hostsAvailable(cidrNotation)) #With an IPv6 address print("With IPv6") ipv6 = IP("2001:0db8:0001:0000:0000:0ab9:C0A8:0102 /64") print("Shortened:", ipv6.shorten()) print("With shortened IPv6") shortenedIPv6 = IP("2001:db8:1::ab9:C0A8:102 /64") print("Lengthened:", shortenedIPv6.lengthen())