Esempio n. 1
0
def Post_Msg(cli):
    os.system('clear')
    tweet = raw_input('\tEnter your tweet: ')
    send_sock.sendall(ip_checksum('Post Tweet') + 'Post Tweet')
    send_sock.sendall(cli + ': ' + tweet)
    menu(cli)
    return
Esempio n. 2
0
def Offline_Msg(cli):
    os.system('clear')
    has_answered = False

    while not has_answered:
        send_sock.sendall(ip_checksum("Offline_messages_request") + 'Offline_messages_request')
        try:
            message  = send_sock.recv(4096)
        except timeout:
            print '\tTimeout - Sever busy'
            continue
        else:
            has_answered = True
            ret = json.loads(message)
            MsgList = ret["msglist"]
            print '\n\t********************'
            print '\n\t' + cli + ' List of Messages:'
            print '\n\t'
            if MsgList == 'No Messages Received':
                print MsgList
            else:
                for i in range(0, len(MsgList)):
                    print MsgList[i]
            print '\n'
    menu(cli)
    return
Esempio n. 3
0
def checksum_valid(chk, seq, header, data):
    checksum = pack('IH' + str(len(data)) + 's', seq, header, data)

    if ip_checksum(checksum) == chk:
        return True
    else:
        return False
Esempio n. 4
0
def read_choice(cli):
    print '\n\t****************************'
    choice = int(raw_input('\n\tPick a menu option: '))
    print '\n\t****************************'
    if choice == 1:
        Offline_Msg(cli)
    elif choice == 2:
        Edit_Sub(cli)
    elif choice == 3:
        Post_Msg(cli)
    elif choice == 4:
        print '\n\t***GoodBye***\n\tLogging You Out'
        has_received = False
        while not has_received:
            send_sock.sendall(ip_checksum('Logging Out') + 'Logging Out')
            reply = send_sock.recv(4096)
            if reply == 'success':
                has_received = True
                send_sock.close()
    elif choice == 5:
        Hashtag_Search(cli)
    elif choice == 6:
        See_followers(cli)
    elif choice == 7:
        Send_Msgs(cli)
    elif choice == 8:
        Del_Friend_Msgs(cli)
    elif choice == 9:
        Del_All_Msgs(cli)
Esempio n. 5
0
def checksum_valid(chk, seq, header, data):
  checksum = pack('IH'+str(len(data))+'s', seq, header, data)

  if ip_checksum(checksum) == chk:
    return True
  else:
    return False
Esempio n. 6
0
def chkpckt(pckt):
    pckt_seq = pckt[0:1]
    pckt_chksum = pckt[1:3]
    pckt_msg = pckt[3:]
    if pckt_chksum == ip_checksum(pckt_msg):
        return (True, pckt_seq, pckt_msg)
    else:
        return (False, pckt_seq, pckt_msg)
Esempio n. 7
0
def mkpkt(seqNum, data):
    global isCorrupt
    chksum = ip_checksum(str(data))
    if isCorrupt == 1 and data == 1:
        isCorrupt = 0
        chksum = 'corrupted'
    pkt = str(seqNum) + str(data) + chksum
    return pkt
Esempio n. 8
0
def login_verification():
    msg_count = 0
    while True:
        connection, address = recv_sock.accept()
        message = connection.recv(4096)

        checksum = message[:2]
        if not ip_checksum(message[2:]) == message[:2]:
            continue
        else:
            s = message[2:]

            temp  = []
            temp = s.split(':')
            if len(temp) == 2:
                name, password = temp[0], temp[1]
            
                found = False
                for cli in cli_list:
                    if cli == [name, password]:
                        found = True
                        break
                if not found:
                    connection.sendall(ip_checksum('Invalid') + 'Invalid')
                    print '\n\t' + name + ' Connection attempt failed\n'
                else:
                    print '\n\t' + name + ' Successfully Logged in\n'
                    
                    connection.sendall(ip_checksum('Valid') + 'Valid')
                    connections[user_id(name)].append(connection)
                    recv_sock.listen(1)

                    live_sock, address = recv_sock.accept()
                    connections[user_id(name)].append(live_sock)
                    
                    print len(connections[user_id(name)])
                    print '\t' + name + ' Live socket connected'
                    #recv_sock.listen(5)

                    t = threading.Thread(target = user_handler, args=(name, connection,))
                    t.daemon = True
                    threads.append(t)
                    t.start()

    recv_sock.close()
Esempio n. 9
0
def Del_All_Msgs(cli):
    os.system('clear')
    send_sock.sendall(ip_checksum('Del_All_Msgs') + 'Del_All_Msgs')
    has_succeeded = False
    while not has_succeeded:
        reply = send_sock.recv(4096)
        if reply == 'success':
            has_succeeded = True
    menu(cli)
    return
Esempio n. 10
0
def makepkt(num, data):
    global iscorrupt
    if iscorrupt == 1 and data == 1:
        iscorrupt = 0
        checksum = 'corrupted'
    else:
        checksum = ip_checksum(str(data))

    packet = str(num) + str(data) + checksum
    return packet
Esempio n. 11
0
def makepkt(num, data):
    global iscorrupt
    if iscorrupt == 1 and data == 2:
        iscorrupt = 0
        checksum = 'corrupted'
        print "packet " + str(data) + "is corrupted, sending "
    else:
        checksum = ip_checksum(str(data))

    packet = str(num) + str(data) + checksum
    return packet
Esempio n. 12
0
def make_packet(seq_num, message):
    """
	Creates a packet using the sequence number and data provided. 
	Calculates checksum of data add concatenates it with data.
	Returns a single string containing sequence number, data, and
	checksum, in that order.
	"""
    tmp = str(seq_num) + message
    checksum = ip_checksum(tmp)
    final_packet = tmp + checksum
    return final_packet
Esempio n. 13
0
def sendwithcheck(sock, msg, to):
    checksum = ip_checksum(msg)
    tosend = checksum+msg

    rand = random.randint(1, 20)
    if rand >= 1 and rand <= 5:
        print("Dropped")
        return

    rand_sleep()
    sock.sendto(tosend, to)
Esempio n. 14
0
def sendwithcheck(sock, msg, to):
    checksum = ip_checksum(msg)
    tosend = checksum + msg

    rand = random.randint(1, 20)
    if rand >= 1 and rand <= 5:
        print("Dropped")
        return

    rand_sleep()
    sock.sendto(tosend, to)
Esempio n. 15
0
def authenticate():
    os.system('clear')
    print '\t***************************'
    cli_name = raw_input('\tUsername: '******'\tPassword: '******'\t***************************'

    print '\n\t****Waiting for server to authenticate your login****\n'

    authentication = cli_name
    authentication += ':' + cli_pwd
    
    ans_received = False
    
    while not ans_received:
        send_sock.sendall(ip_checksum(authentication) + authentication)
        try:
            message = send_sock.recv(4096)
        except timeout:
            print 'Timeout occured -- Server Busy'
            continue
        else:
            if not message[:2] == ip_checksum(message[2:]):
                continue #resend the authentication to server
            else:
                ans_received = True
                if message[2:] == 'Valid':
                    os.system('clear')
                    print '\n\tSuccessful Login!! -- Welcome ' + cli_name
                    
                    live_sock = socket(AF_INET, SOCK_STREAM)
                    live_sock.connect(dest)
                    
                    t = threading.Thread(target = tweets_and_msgs_handler, args=(cli_name, live_sock, ))
                    t.daemon = True
                    t.start()
                    menu(cli_name)
                elif message[2:] == 'Invalid':
                    print '\n\tError: Name or Password entered is invalid -- Try again'
                    authenticate()
    send_sock.close()
Esempio n. 16
0
def corrupt(packet):
    """
	Checks if packet was corrupted during transmission. Calculates
	checksum and compares it to the one included in the packet.
	Returns true if data is corrupted, false otherwise.
	"""
    data = packet[:len(packet) - 2]
    checksum = packet[len(packet) - 2:]
    calculated_check = ip_checksum(data)
    if checksum != calculated_check:
        return True
    return False
Esempio n. 17
0
	def tick(self):
		# Progress all games
		for game in self.db.ongoing_games:
			if game.ongoing : game.tick()
			else : self.db.ongoing_games.remove(game)

		#Receive data from client.
		readable, writable, exceptional = select.select([self.s], [], [], 0);
		d = None
		self.data = ""
		self.reply = ""
		if readable:
			d = self.s.recvfrom(1024)
			data = d[0]
			self.addr = d[1]
			self.source = str(d[1])
			# print 'Handled player request'
		elif not self.data_q.empty():
			d = self.data_q.get(False)
			# print 'Host packet contents : ' + d
			self.route_msg(d)
			return
		else: return

		# Take apart packet
		self.ack = data[4]
		msg = data[5:-2]
		chksum = data[-2:]
		
		'''
		print 'OK... \n' + \
		'Source Port : ' + self.source + '\n' \
		'Ack : ' + self.ack + '\n' + \
		'Data : ' + msg + '\n'# + \
		# 'Checksum : [' + chksum + ']';
		'''

		# print 'This checksum : [' + ip_checksum(msg) + ']'
		if ip_checksum(msg) == chksum: # Not corrupt
			# print 'Routing message to correct control code.'
			self.route_msg(msg)
			self.ack = '0' if (self.ack == '0') else '1'
		else:
			self.ack = '1' if (self.ack == '1') else '0'
		
		#print 'Denying packet for 7.5 seconds...'
		#time.sleep(7.5);
		
		reply = 'ACK' + self.ack + '\n' + str(self.data);
		# print 'Sending reply : ' + reply 
		
		self.s.sendto(reply, (self.addr[0], self.addr[1]));
Esempio n. 18
0
def Edit_Sub(cli):
    os.system('clear')
    print("""\n
    \t1. Add Subscription
    \t2. Delete Subscription
    """)
    choice = int(raw_input('\n\tEnter Your Choice: '))
    if choice == 1:
        send_sock.sendall(ip_checksum('Subscribe') + 'Subscribe')
        friend = raw_input('\n\tEnter Friend to Subscribe to: ')

        has_succeeded = False
        while not has_succeeded:
            send_sock.sendall(cli+friend)
            reply = send_sock.recv(4096)
            if reply == 'success':
                has_succeeded = True
            
    elif choice == 2:
        send_sock.sendall(ip_checksum('Unsubscribe') + 'Unsubscribe')
        reply = send_sock.recv(4096)
        list = json.loads(reply)
        sublist = list["list"]

        if sublist == 'No followers':
            print '\tNo user to Unsubscribe from'
        else:
            for l in sublist:
                print l
            friend = raw_input('\n\tEnter Friend to Unsubcribe from: ')
    
            has_succeeded = False
            while not has_succeeded:
                send_sock.sendall(cli+friend)
                reply = send_sock.recv(4096)
                if reply == 'success':
                    has_succeeded = True
    menu(cli)
    return
Esempio n. 19
0
def Del_Friend_Msgs(cli):
    os.system('clear')
    send_sock.sendall(ip_checksum('Del_Friend_Msgs') + 'Del_Friend_Msgs')
    friend = raw_input("\tEnter friend whose messages to delete: ")
    
    has_succeeded = False
    while not has_succeeded:
        send_sock.sendall(cli + ':' + friend)
        reply = send_sock.recv(4096)
        if reply == 'success':
            has_succeeded = True
    menu(cli)
    return
Esempio n. 20
0
def See_followers(cli):
    os.system('clear')
    send_sock.sendall(ip_checksum('See Followers') + 'See Followers')
    reply = send_sock.recv(4096)
    msg = json.loads(reply)
    subList = msg["subList"]
    print '\n\t' + cli + ' List of Followers: '
    if subList == 'No Followers':
        print subList
    else:
        for i in range(0, len(subList)):
            print subList[i]
    print '\n'
    menu(cli)
    return
Esempio n. 21
0
def Hashtag_Search(cli):
    os.system('clear')
    send_sock.sendall(ip_checksum('Hashtag Search') + 'Hashtag Search')
    hashtag = raw_input('\tEnter the hashtag to search for: ')
    send_sock.sendall(hashtag)
    reply = send_sock.recv(4096)
    msg = json.loads(reply)
    hashList = msg["hashList"]
    print '\n\t' + cli + ' List of tweets containing ' + hashtag + ':'
    if hashList == 'No Tweets Found':
        print hashList
    else:
        for i in range(0, len(hashList)):
            print hashList[i]
    print '\n'
    menu(cli)
    return
Esempio n. 22
0
def Send_Msgs(cli):
    os.system('clear')
    send_sock.sendall(ip_checksum('Send Message') + 'Send Message')
    destinator = raw_input('\n\tEnter destinator: ')
    msg = raw_input('\tEnter Message: ')

    while len(msg) > 140:
        print '\n\tMessage longer than 140 characters -- try again'
        msg = raw_input('\tEnter Message: ')
    
    has_succeeded = False
    while not has_succeeded:
        send_sock.sendall(destinator + cli + ': ' + msg)
        reply = send_sock.recv(4096)
        if reply == 'success':
            has_succeeded = True
    menu(cli)
    return
Esempio n. 23
0
def checksum_cmp (received_content, received_checksum):
  #casting checksum to str by itself is not the same when casting it to str via tuple...
  #when checksum is in tuple and is cast into a string, they are the same
  check = ip_checksum(received_content)
  tuple_pkt = (0,0, check)
  tuple_pkt_str = str(tuple_pkt)
  splice_tuple_pkt = string.split(tuple_pkt_str, ',')
  j = 0
  for i in splice_tuple_pkt:
    i = string.strip(i, '(')
    i = string.strip(i, ')')
    i = string.strip (i) #by default it removes whitespace
    i = string.strip (i, '\'')
    splice_tuple_pkt[j] = i
    j = j + 1
  if splice_tuple_pkt[2] == received_checksum:
    return 1
  else:
    return 0
Esempio n. 24
0
print('Socket bind complete')

expecting_seq = 0

#now keep talking with the client
while 1:
    # receive data from client (data, addr)
    msg, addr = s.recvfrom(1024)

    #msg = msg.decode('utf-8')

    checksum = msg[:2]
    seq = msg[2]
    cont = msg[3:]
    
    if not msg: 
        break

    if ip_checksum(cont) == checksum:
        sendwithcheck(s, "ACK" + seq, addr)
        if seq == str(expecting_seq):
            print('Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + cont)
            expecting_seq = 1 - expecting_seq
            #reply = 'OK...' + data
            #s.sendto(reply.encode('utf-8') , addr)
    else:
        neg_seq = str(1 - expecting_seq)
        sendwithcheck(s, "ACK" + neg_seq, addr)
    
s.close()
Esempio n. 25
0
# use it in this way
#https://www.bogotobogo.com/python/Multithread/python_multithreading_subclassing_Timer_Object.php
# create dgram udp socket

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
    print 'Failed to create socket'
    sys.exit()

host = 'localhost'
port = 8888
seqnum = 0  # sequence number

msg = raw_input('Enter message to send : ')
chks = str(ip_checksum(msg))  #convert checksum return value to string
data = (str(seqnum) + chks + msg)
s.sendto(data, (host, port))

while (1):
    msg = raw_input('Enter message to send : ')

    #chks = str(ip_checksum(msg))					#convert checksum return value to string
    #data = (str(seqnum) + chks + msg)				#all 3 values are strings and merged together
    try:
        # Set the whole string
        # s.sendto(msg, (host, port))
        # s.sendto(data, (host, port))

        # receive data from client (data, addr)
        d = s.recvfrom(1024)
Esempio n. 26
0
PKT = 1  #packet number
N = 4  #window size
TIMEOUT = 10  #timeout time

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
    print 'Failed to create socket'
    sys.exit()

while 1:
    msg = raw_input('Enter message to send : ')
    # msg = msgList[count]
    # old_msg = msg
    # count+=1
    checksum = ip_checksum(msg)  #get checksum of message
    # if msg[0:1] == 'C' and flag==0:
    #   checksum = checksum + "c"
    #   flag = 1
    msg = str(PKT).zfill(3) + str(
        checksum) + msg  #new message: 00PKT+CHKSM+MSG
    pkt_curr = pkt_struct(PKT,
                          msg)  #set current: packet with packet number and msg
    pkt_list.append(pkt_curr)
    PKT += 1  #increment packet number

    try:  #try to send packet
        if (pkt_curr.num < BASE + N):
            pkt_curr.send_pkt(s)  #s.sendto(pkt_curr.msg, (HOST, PORT))
            #pkt_curr.time_sent = time.time()
        inputs = [s]
Esempio n. 27
0

old_msg = ''
resend = 0
count = 1
while(1) :

    try :
	while(1) :
		if nextseqnum >= base + windowSize :
			break
		if nextseqnum > 9 :
			break
	    	msg = str(msgList[nextseqnum])
	        s.settimeout(3)
	        d = ip_checksum(msg)
	        msg_d = d + msg
	        msg_seq_d = str(nextseqnum) + msg_d
	# check corrupted msg
	#    msg_d = 'll' + msg
	        if nextseqnum < base + windowSize :
	            print 'sending... ' + msg_seq_d
	            s.sendto(msg_seq_d, (host, port))
	            nextseqnum = nextseqnum + 1
		else :
			break
	

        # receive data from client (data, addr)
        try:
            data = s.recvfrom(1024)
Esempio n. 28
0
	#receive data from client(data,addr)
	d=s.recvfrom(1024)
	data=d[0]
	addr=d[1]
	rc_seqnum=data[0]
	get_checksum=data[1:3]
	rc_msg=data[3:]


	print 'Message['+addr[0]+':'+str(addr[1])+']-'+rc_msg
	if ( rc_msg==''):
		status=0
		continue

	reply_msg='OK...' +rc_msg
	if ( rc_seqnum==str(expectedseqnum) and get_checksum==ip_checksum(rc_msg) ):
		expectedseqnum=(expectedseqnum+1)%10
		snd_seqnum=str(expectedseqnum)
		snd_checksum=ip_checksum(reply_msg)
		reply=rc_seqnum+snd_seqnum+snd_checksum+reply_msg
		s.sendto(reply,addr)
		print 'expected number is '+str(expectedseqnum)
	else:
		snd_seqnum=str(expectedseqnum)
		snd_checksum=ip_checksum('')
		if expectedseqnum==0:
			ACK=9
		else:
			ACK=expectedseqnum-1
		reply=str(ACK)+snd_seqnum+snd_checksum+''
		s.sendto(reply,addr)
Esempio n. 29
0
signal.signal(signal.SIGALRM, timer_for_ack)
signal.setitimer(signal.ITIMER_REAL, 0.01, 0.01)

winhead = 0

while not sendOver:
  wincur = wintail + 1

  if wincur >= winSize and winhead != wincur and wincur%winSize == winhead%winSize:
    continue

  data = msg_to_send()

  header = int('1111111100000000', 2)
  cs = pack('IH' + str(len(data)) + 's', seqno, header, data)
  checksum = ip_checksum(cs)

  packet = pack('I2sH' + str(len(data)) + 's', seqno, checksum, header, data)

  if wincur < winSize:
    winPkts.append(packet)
    tickers.append(TIMEOUT)
  else:
    winPkts[wincur % winSize] = packet
    tickers[wincur % winSize] = TIMEOUT

  print "Sending P" + str(seqno) + ", timer started"

  if CORRUPT > random.random():
    error_data = "01234567012345678012345678012345678"
    packet = pack('I2sH' + str(len(error_data)) + 's', seqno, checksum, header, error_data)
Esempio n. 30
0
print('Socket bind complete')

expecting_seq = 0

#now keep talking with the client
while 1:
    # receive data from client (data, addr)
    msg, addr = s.recvfrom(1024)

    #msg = msg.decode('utf-8')

    checksum = msg[:2]
    seq = msg[2]
    cont = msg[3:]

    if not msg:
        break

    if ip_checksum(cont) == checksum:
        sendwithcheck(s, "ACK" + seq, addr)
        if seq == str(expecting_seq):
            print('Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + cont)
            expecting_seq = 1 - expecting_seq
            #reply = 'OK...' + data
            #s.sendto(reply.encode('utf-8') , addr)
    else:
        neg_seq = str(1 - expecting_seq)
        sendwithcheck(s, "ACK" + neg_seq, addr)

s.close()
Esempio n. 31
0
inputs=[s]
outputs=[]
timeout=10
while(1):
	input_msg=raw_input('Enter message to send : ')

	try :
		status='a'
		length=2

		while(len(input_msg)>0):
			#Set the whole string
			snd_msg=input_msg[0:length]
			print 'Send message : '+snd_msg
			d=ip_checksum(snd_msg)
			snd_status=status
			send_msg=snd_status+d+snd_msg
			s.sendto(send_msg,(host,port))

			readable,writable,exceptional=select.select(inputs,outputs,inputs,timeout)
			for s in readable:
				#receive data from client (data, addr)
				d=s.recvfrom(1024)
				reply=d[0]
				addr=d[1]
				rc_status=reply[0]
				get_checksum=reply[1:3]
				reply_msg=reply[3:]
	
				print 'Server reply : '+reply_msg
Esempio n. 32
0
def makeack(s, seq, msg):
    ack = seq + ip_checksum(msg) + msg
    return ack
Esempio n. 33
0
  s.bind(("", PORT))
except socket.error, msg :
  print 'Bind failed. Error Code: ' + str(msg[0]) + ' Message ' + msg[1] 
  sys.exit() 

print 'Socket bind complete' 

while 1: 
  d = s.recvfrom(1024)
  data = d[0] 
  addr = d[1] 
  
  if not data: 
    break 

  if data[1:3] != ip_checksum(data[3:]): 
    continue
  
  ACK = data[0] 
  reply = str(ACK) + data[3:]
  s.sendto(reply, addr)
  if ACK != str(PKT): 
    print 'DUPLICATE'
  else: 
    PKT = 0 if PKT else 1
  print 'Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + data.strip()

  #COUNT += 1
  #if COUNT % 3 == 0:
  #  sleep(5)
Esempio n. 34
0
outputs=[]
timeout=10
cwnd=4
base=0
nextseqnum=0
while(1):
	input_msg=raw_input('Enter message to send : ')

	try :
		length=2
		begin=0
		end=2
		while(len(input_msg[0:]) <base or len(input_msg[begin:])>0 ):
			while(len(input_msg[begin:])>0 and nextseqnum<base+cwnd):
				snd_msg=input_msg[begin:end]
				d=ip_checksum(snd_msg)
				snd_seqnum=str(nextseqnum % 10)
				send_msg=snd_seqnum+d+snd_msg
				s.sendto(send_msg,(host,port))

				print 'Send message : '+snd_msg+', sndseqnum :' +snd_seqnum
				nextseqnum=nextseqnum+1
				print 'nextseqnum is '+str(nextseqnum)+', base+cwnd is '+str(base+cwnd)
				sleep(1)
				begin=nextseqnum*length
				if(len(input_msg[nextseqnum*length:])<length):
					end=begin+len(input_msg[nextseqnum*length:])
				else:
					end=(nextseqnum+1)*length

Esempio n. 35
0
print 'Socket bind complete'

inputs = [s]
outputs = []
#ackstatus to return the package 0/1 if received
currAck = 0
testCase = 0
#now keep talking with the client
while 1:
    d = s.recvfrom(1024)
    data = d[0]
    addr = d[1]

    #set the checksum from from the data recieved
    checksum = ip_checksum(data[1:-2])

    if not data:
        break
#Wrong ACK
    if (data[0] != str(currAck)):
        print 'Duplicate Packet'
        continue
#Corrupted checksum
    if (data != (str(currAck) + data[1:-2] + checksum)) and (
            data != (str(not ACKstatus) + data[1:-2] + checkSum)):
        print 'Corrupt'
        continue

#check the test, set a timeout
    if testCase == 1:
Esempio n. 36
0
PKT = 1       #packet number
N = 4         #window size
TIMEOUT = 10  #timeout time

try: 
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:    
  print 'Failed to create socket' 
  sys.exit() 

while 1: 
  msg = raw_input('Enter message to send : jk hardcoded so it doesnt matter ')
  msg = msgList[count]
  old_msg = msg 
  count+=1
  checksum = ip_checksum(msg)                   #get checksum of message
  if msg[0:1] == 'C' and flag==0:
    checksum = checksum + "X"
    flag = 1
  msg = str(PKT).zfill(3) + str(checksum) + msg #new message: 00PKT+CHKSM+MSG
  pkt_curr = pkt_struct(PKT, msg)           #set current: packet with packet number and msg
  pkt_list.append(pkt_curr) 
  PKT += 1                                      #increment packet number

  
  try:                      #try to send packet
    if (pkt_curr.num < BASE + N):
      pkt_curr.send_pkt(s)  #s.sendto(msg, (HOST, PORT)) #gotta send the corrupted msg (not original)
                            #pkt_curr.time_sent = time.time()
    inputs = [s]
    outputs = [] 
Esempio n. 37
0

while 1:
    msg = raw_input("Press anykey to send packets")
    try:
        reset()
        for i in range(2):
            if base == nextseqnum:
                timerStart(base, windowsize)

            while 1:
                d = s.recvfrom(1024)
                reply = d[0]
                ACK = int(reply[0])
                ACKCheckSum = reply[1:]
                CheckSum = ip_checksum(str(ACK))

                if ACKCheckSum == CheckSum:
                    base = ACK + 1
                    if base == nextseqnum:
                        timer.cancel()
                        break
                    else:
                        timer.cancel()
                        timer = threading.Timer(2, timerStart,
                                                [base, windowsize])
                        timer.start()

    except socket.error, msg:
        print 'Error code: ' + str(msg[0]) + 'Message ' + msg[1]
        sys.exit()
Esempio n. 38
0
 inputs = [s] #socket
 outputs = []
 timeout = 0 #when timeout is 0, it basically polls 
 readable, writeable, expectional = select.select(inputs, outputs, inputs, timeout)
 for temp_socket in readable:
   received_data = temp_socket.recvfrom(1024)
   received_packet = received_data[0]
   address = received_data[1]
   print 'Received packet: ', received_packet
   packet_sequence_number, packet_data, packet_checksum = extract_data(received_packet)
   #print packet_sequence_number, packet_data, packet_checksum
   #check if packet has sequence number 1 or 0
   #if 1 then we send an ACK1 back because there was a packet loss and 
   #the sender requires this ACK to make progress. Otherwise, the sender is 'stuck'
   if packet_sequence_number == '1':
     checksum = ip_checksum ('ACK1')
     packet_to_send = make_packet ('1', 'ACK1', checksum)
     #send packet
     s.sendto(str(packet_to_send), address)
   elif packet_sequence_number == '0' and checksum_cmp(packet_data, packet_checksum):
     # we have already extracted the data
     '''
     This is were we would forward the data up the internet protocl stack to 
     the application layer or any intermediate agent between the transport and
     application layer.
     '''
     #send ACK0 to sender
     checksum = ip_checksum ('ACK0')
     packet_to_send = make_packet('0', 'ACK0', checksum)
     #send packet
     s.sendto(str(packet_to_send), address)
Esempio n. 39
0
        #initialize thread list of size 4
        threadList = [None] * windowSize
        #initialize ack list of size 8
        ackList = [error] * maxSeqNum

        for i in range(base, base + windowSize):
            timerStart(nextSeqNum, threadList, i)
            nextSeqNum = nextSeqNum + 1

        while 1:
            d = s.recvfrom(1024)
            reply = d[0]

            ackNum = int(reply[0])
            ackChksum = reply[1:]
            chksum = ip_checksum(str(ackNum))

            #check if ACK is corrupt
            if ackChksum == chksum:
                ackList[ackNum] = ackNum
                #ACK received correctly so cancel timer
                index = ackNum % 4
                threadList[index].cancel()

                print 'ACK ' + str(ackNum) + ' received'

                if base == maxSeqNum - 1:
                    break

                #check if next packet sent is in sender window
                #base + windowSize is packet number
Esempio n. 40
0
  s.bind(("", PORT))
except socket.error, msg :
  print 'Bind failed. Error Code: ' + str(msg[0]) + ' Message ' + msg[1] 
  sys.exit() 

print 'Socket bind complete' 

while 1: 
  d = s.recvfrom(1024)
  data = d[0] 
  addr = d[1] 
  
  if not data: 
    break 

  if data[3:5] != ip_checksum(data[5:]): 
    continue
  
  RCVPKT = int(data[0:3])
  ACK = RCVPKT
  #if not the packet we are waiting for re-ack previous packet
  if RCVPKT != PKT: #not the right packet, send ACK of older packet
    ACK = PKT - 1   #resend the previous PKT
    print 'UNEXPECTED RCVPKT'
  #packet we are waiting for, send next pkt
  else: 
    PKT += 1
  reply = str(ACK).zfill(3) + data[3:]
  s.sendto(reply, addr)
  print 'Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + data.strip()
Esempio n. 41
0
while 1:
    msg = raw_input('press enter to send')
    try:
        reset()
        thelist = [None] * 10000
        acklist = [NACK] * maxseqnum
        for i in range(base, base + windowsize):
            timerStart(nextseqnum, thelist, i)
            nextseqnum = nextseqnum + 1

        while 1:
            d = s.recvfrom(1024)
            reply = d[0]
            Num = int(reply[0])
            check = (reply[1:])
            CheckSum = ip_checksum(str(Num))
            print 'received ack' + str(Num)
            if CheckSum == check:
                acklist[Num] = Num
                index = Num
                thelist[index].cancel()

                if base == maxseqnum - 1:
                    break

                if base == Num and nextseqnum < maxseqnum:
                    index = nextseqnum
                    timerStart(nextseqnum, thelist, index)
                    nextseqnum = nextseqnum + 1
                    base = getbase(acklist, base, windowsize)
            else:
Esempio n. 42
0

old_msg = ''
resend = 0
count =0 
while(1) :
    if base == 10 :
        break
    elif nextseqnum < base + windowSize :
        msg = str(pktList[nextseqnum])
    try :

        s.settimeout(3)
        if msg == '2' :
            if count == 0:
                d = ip_checksum(msg+'1')
                msg_d = d + msg
                msg_seq_d = str(nextseqnum) + msg_d
                count = count + 1
            else:
                d = ip_checksum(msg)
                msg_d = d + msg
                msg_seq_d = str(nextseqnum) + msg_d
        else :
            d = ip_checksum(msg)
            msg_d = d + msg
            msg_seq_d = str(nextseqnum) + msg_d
       
        if nextseqnum < base + windowSize :
            print 'sending... PKT' + msg_seq_d[3:]
            s.sendto(msg_seq_d, (host, port))
Esempio n. 43
0
def makepckt(msg):
    global seq_num
    pckt = seq_num + ip_checksum(msg) + msg

    return pckt
Esempio n. 44
0
 
#now keep talking with the client
while 1:
    inputs = [s]
    outputs = []
    timeout = 5
    readable,writable,exceptional = select.select(inputs,outputs,inputs,timeout)
    for tempSocket in readable:
        temp = tempSocket.recvfrom(1024)
        reply = temp[0]
        addr = temp[1]
        
        ack = reply[0:1]
        msg_sum = reply[1:2]
        msg = reply[3:len(reply)]
        msg_chksum = ip_checksum(msg)
        
        if msg_sum == msg_chksum:
            message = 'received ack ' + reply[0:1]
            s.sendto(message, (HOST, PORT))
        else :
            print 'packet corrupted'
        

            
   


    #s.sendto(reply , addr)
     
s.close()
Esempio n. 45
0
        #                        	print "Resending msg " + str(msg0[0]) + ": " + str(msg0[1:-2])
        #	                        print "Resending msg " + str(msg1[0]) + ": " + str(msg1[1:-2])
        #        	                print "Resending msg " + str(msg2[0]) + ": " + str(msg2[1:-2])
        #                	        print "Resending msg " + str(msg3[0]) + ": " + str(msg3[1:-2])

        #				x = threading.Thread(target = recv_thread, args=(base,))
        #				x.start()
        #				x.join(TIMEOUT)

        #			index = index + 4
        #                	nextseqnum = index % (N * 2 + 1)
        #              	 	base = base +1

        msg = str(nextseqnum) + messages[index] + str(
            ip_checksum(messages[index]))
        s.sendto(msg, (host, port))
        print "Sending msg " + str(msg[0]) + ": " + str(msg[1:-2])

        x = threading.Thread(target=recv_thread, args=(base, ))
        x.start()
        x.join(TIMEOUT)

        while x.isAlive():
            for r in range(base, base + 3):
                msg = str(r % (N * 2 + 1)) + messages[r] + str(
                    ip_checksum(messages[r]))
                s.sendto(msg, (host, port))
                print "Sending msg " + str(msg[0]) + ": " + str(msg[1:-2])

            x = threading.Thread(target=recv_thread, args=(base, ))
Esempio n. 46
0
def user_handler(name, connection):
    user = user_id(name)
    send_offline_tweets(name)

    while True:
        #connection, address = recv_sock.accept()
        message = connection.recv(4096)
        print '\tclient request: ' + name + ' ' + message[2:]
    
        if not message:
            break
            
        elif message[:2] == ip_checksum(message[2:]):
            if message[2:] == 'Offline_messages_request':
                user = user_id(name)
                if len(MsgList[user]) == 0:
                    msg = json.dumps({"msglist" :'No Messages Received'})
                else:
                    msg = json.dumps({"msglist" :MsgList[user]})
                connection.sendall(msg)

            elif message[2:] == 'Send Message':
                message = connection.recv(4096)
                hdr = message[:2]
                if len(connections[user_id(hdr)]) == 0:
                    MsgList[user_id(hdr)].append(message[2:])
                else:
                    connections[user_id(hdr)][1].sendall('live_msg' + message[2:])
                connection.sendall('success')

            elif message[2:] == 'Post Tweet':
                tweet = connection.recv(4096)
                tweetList.append(tweet)
                for j in range(0, len(connections)):
                    st = 'c' + str(j)
                    if  st in subList[user_id(name)]:
                        if len(connections[j]) == 0:
                            off_list_tweets[j].append(tweet)
                        else:                       
                            connections[j][1].sendall('live_twt'+tweet)              
            
            elif message[2:] == 'Del_Friend_Msgs':
                message = connection.recv(4096)
                temp = []
                temp = message.split(':')
                user = temp[0]
                friend = temp[1]
                a = user_id(name)
                lst = MsgList[a]
                for l in lst:
                    if l[:2] == friend:
                        MsgList[a].remove(l)
                connection.sendall('success')

            elif message[2:] == 'Del_All_Msgs':
                a = user_id(name)
                lst = MsgList[a]
                for l in lst:
                    MsgList[a].remove(l)
                connection.sendall('success')
            
            elif message[2:] == 'Subscribe':
                msg = connection.recv(4096)
                friend = msg[2:]
                me = msg[:2]
                subList[user_id(friend)].append(me)
                connection.sendall('success')

            elif message[2:] == 'Unsubscribe':
                unsub = []
                for i in range(0, len(subList)):
                    if name in subList[i]:
                        unsub.append('c'+str(i))
                if len(unsub) == 0:
                    msg = json.dumps({"list" : 'No followers'})
                    connection.sendall(msg)
                else:
                    msg = json.dumps({"list" : unsub})
                    connection.sendall(msg)

                    msg = connection.recv(4096)
                    friend = msg[2:]
                    me = msg[:2]                
                    subList[user_id(friend)].remove(me)
                    connection.sendall('success')
            
            elif message[2:] == 'See Followers':
                if len(subList[user_id(name)]) == 0:
                    msg = json.dumps({"subList" : 'No Followers'})
                else:
                    msg = json.dumps({"subList" : subList[user_id(name)]})
                connection.sendall(msg)
            
            elif message[2:] == 'Hashtag Search':
                msg = connection.recv(4096)
                hashList = []
                for i in range(0, len(tweetList)):
                    if msg in tweetList[i]:
                        hashList.append(tweetList[i])
                if len(hashList) == 0:
                    msg = json.dumps({"hashList" : 'No Tweets Found'})
                else:
                    msg = json.dumps({"hashList" : hashList})
                connection.sendall(msg)

            elif message[2:] == 'Logging Out':
                connection.sendall('success')
                connection.close()
                for c in  connections[user_id(name)]:
                    connections[user_id(name)].remove(c)
                return
    return
Esempio n. 47
0
 def udt_send(self, flag):
     checksum = ip_checksum(self.data)
     sndpkt = self.make_pkt(flag, checksum)
     self.s.sendto(sndpkt, (self.host, self.destport))
Esempio n. 48
0
    print('Resending timed-out packet ' + str(n) + '\n')
    s.sendto(msg, (host, port))
timer = threading.Timer(3.0, pkt_timer)

# Create dgram udp socket

# Client is sender

# Packet # counter
n = 0

# Set up initial packet
# Scenario 1: Packets 0-2
print('\nSending 3 packets normally:\n')
msg = 'packet ' + str(n)
check_sum = ip_checksum(msg)
msg += ';' + str(ord(check_sum[0]) + ord(check_sum[1]))
s.sendto(msg, (host, port))

while(n < 9):
    # msg = raw_input('Enter message to send: ')
    # print('check_sum ' + str(ord(check_sum[0])) + '; pt 2: ' + str(ord(check_sum[1])))

    try:
        if n == 6:
            timer.start()

        # Receive data from client (data, addr)
        d = s.recvfrom(1024)
        reply = d[0]
        addr = d[1]
Esempio n. 49
0
timeout_test = True

# now keep talking with the client
while 1:
    # receive data from client (data, addr)
    data, addr = s.recvfrom(1024)

    checksum = data[:2]
    seq = data[2]
    pkt = data[3:]

    if not data:
        break
    # print(str(ip_checksum(pkt) == checksum))

    if ip_checksum(pkt) == checksum and seq == str(expect_seq):
        print('recv: Good Data Sending ACK' + str(seq))
        print('recv pkt: ' + str(pkt))
        # Test timeout on message 4
        if str(pkt) == 'Message 4':
            time.sleep(5)
        s.sendto(str(seq), addr)
        expect_seq = 1 - expect_seq
    else:
        # Check seq and send according ACK
        if seq == str(expect_seq):
            print('recv: Bad Checksum Not Sending')
        else:
            print('recv: Bad Seq Sending ACK' + str(1 - expect_seq))
            s.sendto(str(1 - expect_seq), addr)
s.close()
Esempio n. 50
0
		print "Failed to create client socket"
		sys.exit()

host = 'localhost'
port = 8888
i = 0
s.settimeout(2)

while(1):
	flag2 = True
	flag = True
	msg = raw_input('Enter message to send: ')
	ackNum = 999
	while flag2:
		try :
			d = ip_checksum(msg)

			if i % 2 == 0:
				ackNum = 0
				if flag:
					tmp = str(ackNum) + "," + str(msg) + "," + "-1"
				else:
					tmp = str(ackNum) + "," + str(msg) + "," + d
			elif i % 2 == 1:
				ackNum = 1
				if flag:
					tmp = str(ackNum) + "," + str(msg) + "," + "-1"
				else:
					tmp = str(ackNum) + "," + str(msg) + "," + d

			sendMessage(tmp, host, port, s)
Esempio n. 51
0
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    print "Socket created"
except socket.error:
    print "Failed to create client socket"
    sys.exit()

try:
    s.bind((HOST, PORT))
    print "Bind socket Created"
except socket.error, msg:
    print "Failed to bind"
    sys.exit()

#temp variable to save the last ack sent
tmpAck = -1
while 1:
    d = s.recvfrom(1024)
    data = d[0]
    addr = d[1]
    x = data.split(",")

    if x[2] != ip_checksum(x[1]):
        print "Packet was lost"
        reply = str(tmpAck)
    else:
        if x[0] == "0" or x[0] == "1":
            reply = str(x[0])
            tmpAck = x[0]

    s.sendto(reply, addr)
Esempio n. 52
0
        break
    
    # Split input into data and checksum
    #print('data = ' + str(data))
    data = data.split(';', 1)
    #print('data[1] = ' + data[1])
    checksum_exp = int(data[1])
    data = data[0]

    print('Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + data.strip())

    #print('checksum_exp = ' + str(checksum_exp))
    #print('checksum_exp type = ' + str(type(checksum_exp)))
    #print('data = ' + data)

    checksum_actual = ip_checksum(data)
    checksum_actual = ord(checksum_actual[0]) + ord(checksum_actual[1])
    #print('checksum_actual = ' + str(checksum_actual))
    #print('checksum_actual type = ' + str(type(checksum_actual)))

    if not corrupted_sent and data == 'packet 4':
        checksum_actual += 1
        corrupted_sent = True

    if checksum_exp != checksum_actual:
        reply = 'CORRUPTED: ' + data
        print(reply)
        print('\tchecksum_exp = ' + str(checksum_exp))
        print('\tchecksum_actual = ' + str(checksum_actual))

    else:
    sys.exit()

# Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error, msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

# Variables
ExpectedSeqNum = 0
N = 4
msg = "ACK" + str(ExpectedSeqNum)
check = ip_checksum(msg)
packet = str(ExpectedSeqNum) + str(len(msg)) + msg + check
rcvpkts = []
base = 0

#now keep talking with the client
while 1:
    # receive data from client (data, addr)
    d = s.recvfrom(1024)
    packet = d[0]
    SeqNum = int(packet[0])
    datalength = int(packet[1])
    data = packet[2:datalength + 2]
    check = packet[datalength + 2:]
    addr = d[1]
Esempio n. 54
0
    print 'Failed to create socket. Error Code : ' + str(
        msg[0]) + ' Message ' + msg[1]
    sys.exit()

# Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error, msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'
ExpectedSeqNum = 0

msg = "ACK" + str(ExpectedSeqNum)
check = ip_checksum(msg)
packet = str(ExpectedSeqNum) + str(len(msg)) + msg + check

#now keep talking with the client
while 1:
    # receive data from client (data, addr)
    d = s.recvfrom(1024)
    packet = d[0]
    SeqNum = int(packet[0])
    datalength = int(packet[1])
    data = packet[2:datalength + 2]
    check = packet[datalength + 2:]
    addr = d[1]

    if not data:
        break
Esempio n. 55
0
    print 'Timed Out: Retry sending Packet' + str(SeqNum)
    msg = 'Hello ' + str(SeqNum)
    check = ip_checksum(msg)
    packet = str(SeqNum) + str(len(msg)) + msg + check
    s.sendto(packet, (host, port))


Corrupt = raw_input("Do you want there to be a corrupt packet?(Y or N)")

while (1):
    progress = raw_input("Press Enter to send more packets")
    for i in range(0, j):
        t = threading.Timer(2.0, Timeout)
        msg = 'Hello ' + str(SeqNum)
        if i == 1 and Corrupt == 'Y':
            check = str(1) + ip_checksum(msg)
        else:
            check = ip_checksum(msg)
        packet = str(SeqNum) + str(len(msg)) + msg + check

        try:
            #Send the whole string
            t.start()
            s.sendto(packet, (host, port))
            d = s.recvfrom(1024)
            packet = d[0]
            AckNum = int(packet[0])
            replylength = int(packet[1])
            reply = packet[2:replylength + 2]
            check = packet[replylength + 2:]
            addr = d[1]
Esempio n. 56
0
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

seq_num = '100'  # bogus initial value
while 1:
    d = s.recvfrom(1024)
    data = d[0]
    addr = d[1]

    if not data:
        break

    prev_sn = seq_num
    seq_num = data[0]

    if data[-2:] != ip_checksum(data[1:-2]):
        print 'Packet corrupted'
    else:
        reply = 'ACK' + str(seq_num)
        # Add for scenario 3: time.sleep(8)
        s.sendto(reply, addr)

    if seq_num != prev_sn:
        print 'Message[' + addr[0] + ':' + str(
            addr[1]) + '] - ' + data.strip()[1:-2]
    else:
        print 'Duplicate detected'
s.close()
Esempio n. 57
0
def Timeout():
    print 'Timed Out: Retry sending Packet' + str(SeqNum)
    msg = 'Hello ' + str(SeqNum)
    check = ip_checksum(msg)
    packet = str(SeqNum) + str(len(msg)) + msg + check
    s.sendto(packet, (host, port))
Esempio n. 58
0
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()
	 
print 'Socket bind complete'

#states for GBN receiver
states = ['wait']
states_list = list(enumerate(states))
current_state = states_list[0]

delay_ack1 = 0
#packet1_corrput = 0

expected_seq_num = 0
msg = 'ACK' + str (expected_seq_num)
checksum = ip_checksum(msg)
#create packet
packet_to_send = make_packet(str(expected_seq_num), msg, checksum)

#related variables for select
inputs = [s] #socket
outputs = []
timeout = 0 #when timeout is 0, it basically polls 
readable = []
writeable = []
expectional =[]
#now keep talking with the client
while 1:
  if current_state == states_list[0]:
    
    readable, writeable, expectional = select.select(inputs, outputs, inputs, timeout)
Esempio n. 59
0
while(1) :
    
    seq = 0

    try :
        while True:
            msg = raw_input('Enter message to send(Q for quit): ')

            if msg == 'Q' or msg == 'q':
                sys.exit()

            ack_received = False
            while not ack_received:

                #Set the whole string
                tosend = ip_checksum(msg) + str(seq) + msg

                rand = random.randint(1, 20)
                if rand >= 1 and rand <= 5:
                    print("Corrupted")
                    tosend = corrupt(tosend)

                s.sendto(tosend, (host, port))
                
                # receive data from client (data, addr)
                try:
                    reply, addr = s.recvfrom(1024)
                except socket.timeout:
                    print('Timeout')
                else: