Пример #1
0
def tcp(ip: str, sender: int, receiver: int):
    """
    :param ip: ip address to send tcp packets
    :param sender: sender port
    :param receiver: receiver port
    :return: void
    """
    # i created a separate class to process files and split them accordingly.
    # for further information, you may refer to the packet.py file.
    file_name = "transfer_file_TCP.txt"
    p = Packet(file_name)
    packet_count = p.packet_count
    # opening the socket using try-with-resources method
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        # bind to the sender port to receive responses using that
        s.bind(('0.0.0.0', sender))
        # get data split as packets using the packet.py methods
        packets = list(p.split_data())
        # connect to the server using the ip and the port
        s.connect((ip, receiver))
        # a header was implemented to send file name, timestamp and packet count.
        header = util.generate(file_name, time(), packet_count)
        # send the header before sending the data packets.
        s.send(header.encode())
        # send data packets
        for i in range(packet_count):
            s.sendall(packets[i])
Пример #2
0
def test_generator():
    for _test, browser in generate(__name__):
        yield _test, browser
 def test_generator():
     for _test, browser in generate(__name__):
         yield _test, browser
Пример #4
0
        test_pred['pred_latitude'] = test_pred['relative_latitude'] / pow(
            10, 20) + X_test['Latitude_1']

        split_dist = util.distance_evaluation(test_pred, y_test)
        splits_dist.append(split_dist)

    dist_df = X_test[main_bs_cols]
    dist = get_average_dist(splits_dist)
    dist_df['dist'] = dist
    pickle.dump(dist_df, open(params.e_errors_pkl, 'wb'))


if __name__ == '__main__':
    train_flag = 0
    if train_flag:
        data = util.generate(fillna_with_0=True)
        data = get_relative_pos(data)
        print(data[relaive_gps_cols].isnull())
        data = util.drop(data,
                         cols=['SignalLevel', 'AsuLevel', 'IMSI', 'MRTime'])
        train(data)
        plot(file=[params.c_errors_pkl, params.e_errors_pkl])
        plot_median_errors_comparison(file=[
            params.c_errors_pkl, params.d_errors_pkl, params.e_errors_pkl
        ])

    else:
        plot(file=[
            params.c_errors_pkl, params.d_errors_pkl, params.e_errors_pkl
        ])
        plot_median_errors_comparison(file=[
Пример #5
0
def udp(ip: str, sender: int, receiver: int):
    """
    :param ip: ip address to send tcp packets
    :param sender: sender port
    :param receiver: receiver port
    :return:
    """
    # i created a separate class to process files and split them accordingly.
    # for further information, you may refer to the packet.py file.
    file_name = "transfer_file_UDP.txt"
    p = Packet(file_name)
    packet_count = p.packet_count
    # get data split as packets using the packet.py methods
    packets = list(p.split_data_for_udp())
    # generate the header to send as the first package
    header = util.generate(file_name, time(), packet_count)
    header_sent = False  # flag to check if header was sent
    packets_sent = [False] * packet_count  # flag to check if packets sent
    last_sent = 0  # id of the last successfully sent package
    retry_count = 0  # retry counter

    # opening the socket using try-with-resources method
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        # i set the timeout as a second
        s.settimeout(1)
        # bind to the port
        s.bind(('', sender))
        # try to send the header first
        while header_sent is False:
            s.sendto(header.encode(), (ip, receiver))
            try:
                # as a response to the header, we need to check the ACK
                response, _ = s.recvfrom(2048)
                if response.decode() == header:
                    # if we receive the header back, it means the header reached
                    # set flag
                    header_sent = True
            except Exception:
                # header was not retrieved, resend
                retry_count += 1
                continue
        # if we have unsent packages, continue until they're complete
        while packets_sent.count(False) != 0:
            # generate the udp parcel to be sent using the first unsent packet
            parcel = p.generate_udp(*packets[last_sent])
            # send parcel
            s.sendto(parcel, (ip, receiver))
            try:
                # check if we get an ACK
                response, _ = s.recvfrom(2048)
                # read parcel nr and hash from the data
                parcel_nr, _, _, hashed = Packet.read_data_for_udp(parcel)
                # if the response is the correct hash, consider as ACK
                if response.decode() == hashed:
                    # if this is the first unsent package, set it as sent
                    # increment last_sent value by 1
                    # else, we have packets prior to this one, ignore this yet
                    if packets_sent.index(False) == parcel_nr:
                        packets_sent[parcel_nr] = True
                        last_sent += 1
            except Exception:
                # not received within time limit, retry
                retry_count += 1
                continue
        # file transfer complete
    print(f"UDP Transmission Re-transferred Packets: {retry_count}")
Пример #6
0
import util

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='GAN')
    parser.add_argument('--set',
                        type=str,
                        help="Accepted values: {mnist, cifar10}")
    parser.add_argument('--train',
                        default=False,
                        action='store_true',
                        help='If set the training procedure is done')
    args = parser.parse_args()

    if args.set == 'mnist':
        import mnist as gan
        output = './resources/mnist/'
    elif args.set == 'cifar10':
        import cifar_10 as gan
        output = './resources/cifar_10/'
    else:
        print('Invalid data set')
        exit(1)

    checkpoint_prefix = output + 'ckpt'
    util.generate(output, gan, output, checkpoint_prefix, args.train)
import pickle
import util

# 50000 - Adversarial training samples
# 10000 - Adversarial test samples

adversarial_samples_training_set = util.generate_using_training_set(556)
fname = 'adversarial_samples_training_set.pkl'
pickle.dump(adversarial_samples_training_set, open(fname, 'wb'))

adversarial_samples_test_set = util.generate(112)
fname = 'adversarial_samples_test_set.pkl'
pickle.dump(adversarial_samples_test_set, open(fname, 'wb'))
Пример #8
0
def udp(ip: str, port: int):
    """
    :param ip: ip address to receive data from (not used)
    :param port: port to listen to
    :return:
    """
    parcels = []  # list of data parcels
    file_name = ""  # file name
    file = b''  # received data
    timestamp = [[0, 0]]  # start and finish timestamps
    packet_count = 0  # total nr of packets
    header_received = False  # flag to check if header was received
    packets_received = [False
                        ]  # list to check the first packet that did not arrive

    # try-with-resources for connection
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        # bind to the port
        s.bind(('', port))
        # loop until all data is received
        while True:
            # read 2048 bytes of data every loop
            data, client_address = s.recvfrom(2048)
            # if data is valid, handle it, else wait until data arrives
            if data:
                # if header was not received, treat the first packet as header
                if not header_received:
                    # try to decipher the data as header
                    header_try = util.decipher(data)
                    # if header can be parsed, then it is a valid header
                    # else wait until header
                    if header_try is not False:
                        # try to split header, since it might be corrupted
                        try:
                            file_name, timestamp[0][
                                0], packet_count, data = header_try
                            # create the same header using the parsed data
                            new_header = util.generate(file_name,
                                                       timestamp[0][0],
                                                       packet_count)
                            # send it back as ACK
                            s.sendto(new_header.encode(), client_address)
                            # mark header received flag as True
                            header_received = True
                            # resize parcels list according to the packet count
                            parcels = [b""] * packet_count
                            # add first package receive time
                            timestamp[0][1] = time()
                            # resize timestamp list according to the packet count
                            timestamp_append = [[0, 0]] * packet_count
                            timestamp += timestamp_append
                            # resize packets received list according to the packet count
                            packets_received = [False] * packet_count
                        except Exception:
                            pass
                else:
                    # header was received already, treat the data as parcel
                    r = Packet.read_data_for_udp(data)
                    # if the data is a valid parcel, use and ack it
                    if r is not False:
                        parcel_nr, timestamp_p, parcel, hashed = r
                        # if the parcel nr is not registered, treat it as new
                        if not packets_received[parcel_nr]:
                            # save parcel, timestamp, and mark parcel as received
                            parcels[parcel_nr] = parcel
                            timestamp[parcel_nr + 1] = timestamp_p, time()
                            packets_received[parcel_nr] = True
                        # send ACK
                        s.sendto(hashed.encode(), client_address)
            # if all packets were received, break from the loop
            if packets_received.count(False) == 0:
                break

    # merge parcels
    for parcel in parcels:
        file += parcel
    # write to file
    with open(file_name, "wb") as file_pointer:
        file_pointer.write(file)
    # calculate time differences
    time_differences = [t[1] - t[0] for t in timestamp]
    udp_average = (sum(time_differences) / len(time_differences)) * 1000
    udp_total = (timestamp[-1][1] - timestamp[0][0]) * 1000
    print(f"UDP Packets Average Transmission Time: {udp_average} ms")
    print(f"UDP Communication Total Transmission Time: {udp_total} ms")