Demo entry 5958794

Sender, Channel, Receiver

   

Submitted by anonymous on Sep 09, 2016 at 01:33
Language: Python 3. Code size: 12.3 kB.

"""Sender program which creates data packets and sends them to receiver via 
transmission medium channel, and waits on response packets from receiver.
Written by Hazel Erickson and Kaitlin Haines, 2016"""

import sys
import socket
import select
import os.path
from struct import *

class packet(object):
    
    def __init__(self, packet_type, seqno, dataLen, data):
        self.magicno = 0x497E
        # data Packet = 1, acknowledgement Packet = 0
        self.packet_type = packet_type 
        self.seqno = seqno # integer value
        self.dataLen = dataLen # integer value between 0 and 512
        self.data = data # field containing the actual user data
        
    def pack(self):
        b = pack("!I3i" + str(self.dataLen) + "s", self.magicno, 
                 self.packet_type, self.seqno, self.dataLen, self.data)
        return b

# command line $python myfile.py var1 var2 var3 filename

# port numbers for the two sender sockets
port_1 = int(sys.argv[1])
port_2 = int(sys.argv[2])

# port number for the channel socket
port_3 = int(sys.argv[3])

# file name
filename = sys.argv[4]

host = '127.0.0.1'    # Loopback address    

seqno_next = 0
exit_flag = False
exit_flag2 = False
packets_sent = 0
read_amount = 0

# Create socket s_out and s_in to sendand receive packets
if ((port_1, port_2 > 1024) and (port_1, port_2 < 64000)):
    print("Creating sockets")
    try:
        s_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    except socket.error:
        print('Failed to create socket s_in') 
        
    try:
        s_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    except socket.error:
        print('Failed to create socket s_out')
    
    # Bind s_in and s_out
    print("Binding sockets")
    s_in.bind((host, port_1))
    s_out.bind((host, port_2))     
    
    # Connect s_out to the host and port
    print("Connecting s out to cs in")
    s_out.connect((host, port_3))
    
    # s_out.sendto(package.encode()) not required 
    # Check filename exists
    if not os.path.exists(filename):
        sys.exit()  
        
    while exit_flag == False:
        # Attepts to read up to 512 bytes from the open file
        with open(filename, mode='rb+') as file:
            print("Reading data from file")
            file.seek(read_amount)
            data = file.read(512)
            read_amount += 512
            
        # Checks size of data and create data packet
        if len(data) == 0:
            print("Creating empty packet")
            size = 0
            data_packet = packet(1, seqno_next, 0, b'')
            packed_data = data_packet.pack()     
            exit_flag = True
            packets_sent += 1
        else:
            print("Creating data packet")
            data_packet = packet(1, seqno_next, len(data), bytes(data))
            packed_data = data_packet.pack()
            packets_sent += 1
            

        exit_flag2 = False
       
        while exit_flag2 == False: 
            print("Sending packet to channel")
            try:
                s_out.sendto(packed_data, (host, port_3))
                packets_sent = packets_sent + 1
            except ConnectionRefusedError:
                print("Connection lost")
            
            readable, _, _ = select.select([s_in], [], [], 1)
            
            print("Checking if s_in is readable")
    
            if readable:
                data_packet2, addr = s_in.recvfrom(1024)
                
                magicno, packet_type, seqno, length = unpack_from("!I3i", data_packet2[:16])
                unpacked_data = unpack_from("%ds" % length, data_packet2[16:])   
                
                if (int(magicno) == 18814):
                    if (length == 0):
                        if (packet_type == 0):
                            if exit_flag == True:
                                print("Packets sent: " + str(packets_sent))
                                s_in.close()
                                s_out.close()
                                sys.exit()                            
                            if seqno == seqno_next:      
                                exit_flag2 = True
                                
                        seqno_next = 1 - seqno_next
                        
            else: print("TIMEOUT")
            
    
else:
    print("Incorrect port size")
                


"""Channel program which sends and receives packets from sender and receiver, 
acts as a transmission medium which can lose packets at a loss rate of P.
Written by Hazel Erickson and Kaitlin Haines, 2016"""

import sys
import socket
import select
import random
from struct import *

#command line $python myfile.py var1 var2 var3 ... 

#hosts for channel
port_1 = int(sys.argv[1])
port_2 = int(sys.argv[2])
port_3 = int(sys.argv[3])
port_4 = int(sys.argv[4])

#host for sender
port_5 = int(sys.argv[5])

#host for receiver
port_6 = int(sys.argv[6])

#packet loss rate
packet_loss_rate = float(sys.argv[7])

host = '127.0.0.1'

#packet loss rate, 0 <= P < 1
if 0 <= packet_loss_rate < 1:
    print("Creating and binding sockets")
    try: 
        cs_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #port_1
        cs_in.bind((host, port_1))
    except socket.error:
        print('Failed to create cs_in socket')
        
    try:
        cs_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #port_2
        cs_out.bind((host, port_2))
    except socket.error:
        print('Failed to create cs_out socket')
          
    try:
        cr_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #port_3
        cr_in.bind((host, port_3))
    except socket.error:
        print('Failed to create cr_in socket')
    
    try:
        cr_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #port_4
        cr_out.bind((host, port_4))
    except socket.error:
        print('Failed to create cr_out socket')
       
    # Set default receivers to the port numbers 
    print("Connecting sockets cs out and cs in to sender and receiver")
    cs_out.connect((host, port_5))
    cr_out.connect((host, port_6))
    
    while True:
        readable, writeable, error = select.select([cs_in], [], [], 1)
        
        if readable: # Ensure we can now read from the socket 
            
            print("Receiving and decoding data")
            packed_data, addr = cs_in.recvfrom(1024)
            
            magicno, packet_type, seqno, length = unpack_from("!I3i", packed_data[:16])
            unpacked_data = unpack_from("%ds" % length, packed_data[16:])     
            
            # Check magicno is '0x497E', else processing is stopped
            if (magicno == 0x497E):
                
                # Generate a random variable between 0 and 1
                random_uniform = random.random()
                
                # Ensures the packet will not be further processed if (u < P)
                if (random_uniform >= packet_loss_rate):
                    
                    # Send the packet via cr_out to the receiver r_in
                    print("Sending to receiver")
                    try:
                        cr_out.sendto(packed_data, (host, port_6))
                    except ConnectionRefusedError: 
                        print("Connection lost")
                        
        readable, writeable, error = select.select([cr_in], [], [], 1)
               
        if readable: # Ensure we can now read from the socket 
            print("Receiving and decoding data")
            packed_data, addr = cr_in.recvfrom(1024)
            
            magicno, packet_type, seqno, length = unpack_from("!I3i", packed_data[:16])
            unpacked_data = unpack_from("%ds" % length, packed_data[16:])
            
            # Check magicno is '0x497E', else processing is stopped
            if (magicno == 0x497E):
                
                # Generate a random variable between 0 and 1
                random_uniform = random.random()
                
                # Ensures the packet will not be further processed if (u < P)
                if (random_uniform >= packet_loss_rate):
                    
                    # Send the packet via cr_out to the receiver r_in
                    print("Sending to sender")
                    try:
                        cs_out.sendto(packed_data, (host, port_5))
                    except ConnectionRefusedError:
                        print("Connection lost")
        else:
            print("TIMEOUT")       
    
else:
    print("Incorrect packet loss rate")
    

        
        
    
    
    
"""Receiver program that receives packets from sender via the transmission 
medium channel, sends back response packets, and writes the packet data to file.
Written by Hazel Erickson and Kaitlin Haines, 2016"""

import socket
import select
import sys
import os
from struct import *

class packet(object):
    
    def __init__(self, packet_type, seqno, dataLen, data):
        self.magicno = 0x497E
        # data Packet = 1, acknowledgement Packet = 0
        self.packet_type = packet_type 
        self.seqno = seqno # integer value
        self.dataLen = dataLen # integer value between 0 and 512
        self.data = data # field containing the actual user data
        
    def pack(self):
        b = pack("!I3i" + str(self.dataLen) + "s", self.magicno, 
                 self.packet_type, self.seqno, self.dataLen, self.data)
        return b

port_1 = int(sys.argv[1])
port_2 = int(sys.argv[2])
port_3 = int(sys.argv[3])
workfile = sys.argv[4]
host = '127.0.0.1'

print("Creating and binding sockets")
try:
    r_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    r_in.bind((host, port_1))
except socket.error:
    print('Failed to create socket')
       
try:
    r_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    r_out.bind((host, port_2))
except socket.error:
    print('Failed to create socket')

print("Connecting sr_in")
r_out.connect((host, port_3))
       
if not os.path.exists(workfile):
    document = open(workfile, "w")
else:
    ("File already exists")
    sys.exit()
  
expected = 0
not_done = True

while not_done == True:   
    
    readable, _, _ = select.select([r_in], [], [], 1)
    print("Checking r in is readable")
    if readable:
        
        packed_data, addr = r_in.recvfrom(1024)
        
        magicno, packet_type, seqno, length = unpack_from("!I3i", packed_data[:16])
        unpacked_data = unpack_from("%ds" % length, packed_data[16:]) 
        
        # Check magicno is '0x497E', else processing is stopped
        print("Check magicno and packet type")
        if magicno == 0x497E and packet_type == 1:
         
            # Create and send a packet
            print("Create and send a packet")
            if seqno != expected:
                ack_packg = packet(0, 0, 0, b'')
                packed_data = ack_packg.pack() 
                try:
                    r_out.sendto(packed_data, (host, port_3))
                except ConnectionRefusedError:
                    print("Connection lost")
                
            if seqno == expected:
                ack_packg = packet(0, 0, 0, b'')
                packed_data = ack_packg.pack()
                try:
                    r_out.sendto(packed_data, (host, port_3))
                except ConnectionRefusedError:
                    print("Connection lost")                    
                
                if length > 0:
                    document.write(unpacked_data[0].decode())
                    print("Wrote to file")
                elif length == 0:
                    r_in.close()
                    r_out.close()
                    sys.exit() 
            
            expected = 1 - expected          
                    
    else:
        print("TIMEOUT")
             
else:
    sys.exit()

       
        

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).