Esempio n. 1
0
def gotoSendFile(pool, sMain):
    global currentPortAddress
    filepaths = askopenfilenames()
    num_files = len(filepaths)
    send(sMain, "Length" + SEPARATOR + str(num_files) + "\n", 'utf-8')
    print("send", num_files)
    #msg=receive(sMain,BUFFER_SIZE_VERY_SMALL,'utf-8')
    req = ""
    while True:
        msg = receive(sMain, 1, 'utf-8')
        print(msg, end="")
        if (msg != '\n'):
            req += msg
        else:
            req += msg
            break
    ports = []
    if (req == RECEIVING_ACK):
        for filepath in filepaths:
            filename = os.path.basename(filepath)
            filesize = int((os.stat(filepath)).st_size)
            currentPortAddress += 2
            fileInfo = filename + SEPARATOR + str(filesize) + SEPARATOR + str(
                currentPortAddress) + "\n"
            ports.append(currentPortAddress)
            send(sMain, fileInfo, 'utf-8')
        msg = receive(sMain, BUFFER_SIZE_SMALL, 'utf-8')
        if (msg == RECEIVING_ACK):
            #file data is sent, now send the files on separate threads
            i = 0
            #			print("its done ipto sending data")
            for filepath in filepaths:
                filesize = int((os.stat(filepath)).st_size)
                pool.apply_async(sendFile,
                                 args=(
                                     filepath,
                                     i,
                                     ports[i],
                                     filesize,
                                 ))
                i += 1

        pool.close()
        pool.join()
        currentPortAddress -= 2 * num_files
        return True
    print("File cant  be reached: FILEOPENERROR")
    return False
Esempio n. 2
0
    def cmdloop(self):

        while not self.flag:
            try:
                sys.stdout.write(self.prompt)
                sys.stdout.flush()

                # Wait for input from stdin & socket
                inputready, outputready,exceptrdy = select.select([0, self.sock], [],[])
                
                for i in inputready:
                    if i == 0:
                        data = sys.stdin.readline().strip()
                        if data: send(self.sock, data)
                    elif i == self.sock:
                        data = receive(self.sock)
                        if not data:
                            print('Shutting down.')
                            self.flag = True
                            break
                        else:
                            sys.stdout.write(data + '\n')
                            sys.stdout.flush()
                            
            except KeyboardInterrupt:
                print('Interrupted.')
                self.sock.close()
                break
Esempio n. 3
0
def recvGetline(sMain):
    msg = ""
    while True:
        ch = receive(sMain, 1, 'utf-8')
        msg += ch
        if (ch == '\n'):
            break
    return msg
Esempio n. 4
0
def check_conn(s):
    send(s, CONNECTION_ESTABLISHED_SERVER, 'utf-8')
    ack = receive(s, BUFFER_SIZE_VERY_SMALL, 'utf-8')
    if (ack == RECEIVING_ACK):
        #the sent packet is acknowledged
        print("UPLOADING SUCCESS")
        globalUpl = 1
    else:
        print("UPLOADING FAILED")
        globalUpl = 0
        s.close()
    msg = receive(s, BUFFER_SIZE_VERY_SMALL, 'utf-8')
    if (msg == CONNECTION_ESTABLISHED_CLIENT):
        #the message is received
        send(s, RECEIVING_ACK, 'utf-8')
        print("DOWNLOADING SUCCESS")
        globalDown = 1
    else:
        print("DOWNLOADING FAILED")
        globalDown = 0
        s.close()
Esempio n. 5
0
def sendFile(filepath, i, port, filesize):
    try:
        import socket
        import os
        from constants import BUFFER_SIZE_MEDIUM, SEPARATOR
        from wifiUtils import getIpAddress
        from main import send
        from main import receive
        print("Port :", port)
        subsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        subsock.bind((getIpAddress(), port))

        subsock.listen()
        print("Waiting", i)
        conn, addr = subsock.accept()
        print("Connection established", i, addr)
        msg = "REQUEST_TO_SEND" + SEPARATOR + str(i) + "\n"
        send(conn, msg, 'utf-8')
        recv = ""
        while True:
            ch = receive(conn, 1, 'utf-8')
            if (ch != '\n'):
                recv += ch
            else:
                recv += ch
                break
        exp = "ALLOW_TO_RECV" + SEPARATOR + str(i) + "\n"
        if (recv == exp):
            print("request accepted", i)
            #sending file by bytes
            f = open(filepath, "rb")
            byte = f.read(BUFFER_SIZE_MEDIUM)
            count = 0
            a = 0
            print("Sending in progress", end=" ")
            while byte:
                send(conn, byte)
                byte = f.read(BUFFER_SIZE_MEDIUM)
                count += len(byte)
                #print(".",end="")
            rem = filesize % BUFFER_SIZE_MEDIUM
            byte = f.read(rem)
            send(conn, byte)
            conn.close()
        else:
            print("receiving not allowed")
            conn.close()
    except Exception as ex:
        print(ex)
Esempio n. 6
0
 def __init__(self, name, host='127.0.0.1', port=3490):
     self.name = name
     # Quit flag
     self.flag = False
     self.port = int(port)
     self.host = host
     # Initial prompt
     self.prompt='[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> '
     # Connect to server at port
     try:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.sock.connect((host, self.port))
         print('Connected to chat server@%d' % self.port)
         # Send my name...
         send(self.sock,'NAME: ' + self.name) 
         data = receive(self.sock)
         # Contains client address, set it
         addr = data.split('CLIENT: ')[1]
         self.prompt = '[' + '@'.join((self.name, addr)) + ']> '
     except socket.error, e:
         print('Could not connect to chat server @%d' % self.port)
         sys.exit(1)
Esempio n. 7
0
def receiveFile(filename, filesize, port, i):
    try:
        import os
        import socket
        from constants import BASEPATH, BUFFER_SIZE_MEDIUM, REQUEST_TO_SEND, SEPARATOR, ALLOW_TO_RECV
        from wifiUtils import getIpAddress
        from main import send, receive, recvGetline
        f = open(BASEPATH + filename, "wb")
        subSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        subSock.bind((getIpAddress(), port))
        subSock.listen()
        print("Socket for ", i, " created")
        conn, addr = subSock.accept()
        print("connection created ", addr)
        #msg="REQUEST_TO_SEND"+SEPARATOR+str(i)+"\n"
        #send(conn,msg,'utf-8')
        msg = recvGetline(conn)
        #print(msg)
        msg = msg.split(SEPARATOR)
        msg[0] += "\n"
        if (msg[0] == REQUEST_TO_SEND and int(msg[1]) == i):
            print("Request arrived")
            msg = "ALLOW_TO_RECV" + SEPARATOR + str(i) + "\n"
            send(conn, msg, 'utf-8')

            iter = filesize
            print("iter", iter)
            while True:
                bytes_read = receive(
                    conn, BUFFER_SIZE_MEDIUM)  #conn.recv(BUFFER_SIZE_MEDIUM)
                iter -= len(bytes_read)
                f.write(bytes_read)
                if (iter <= 0):
                    break
            print("File is saved ", i)
        subSock.close()
    except Exception as ex:
        print(ex)
Esempio n. 8
0
if __name__ == "__main__":
    conf = load_config()
    if len(sys.argv) < 2:
        print(
            "you must set as first argument \"send\", \"receive\" or \"mitm\"")
        exit(0)
    elif sys.argv[1] == "send":
        if len(sys.argv) != 4:
            print(
                "send should have only two arguments: <destination> and <filename>"
            )
            exit(0)
        send(conf, sys.argv[2], sys.argv[3])
    elif sys.argv[1] == "receive":
        if len(sys.argv) != 4:
            print(
                "send should have only two arguments: <port> <recv_filename>")
            exit(0)
        receive(conf, sys.argv[2], sys.argv[3])
    elif sys.argv[1] == "mitm":
        if len(sys.argv) != 6:
            print(
                "send should have only four arguments: <recv_port> <dest_ip> <dest_port> <recv_filename>"
            )
            exit(0)
        mitm(conf, sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    else:
        print(
            "the first argument can be only \"send\", \"receive\" or \"mitm\"")
        exit(1)