Hi,
We have a exercise to hand over in the few days to come. I tried to do it, I done most of the job but I am kind of stuck.
ftclient <host> <port> <filename> <save as>
ftserver <port> <size of each package> <delay between sent package>
The client sends a filename to the server.
If the server has the file, it sends 4 bytes to the client, which are size of the file (Using the stat() function on the server side). Else it sends one byte of 0xff, and the client closes the socket and unlink the file.
If the file exist, the client gets ready to receive the packages.
If in 10 seconds no pack arrives (I used select() ), the client aborts.
If a package arrives, it has 1 byte of success, 4 bytes of offset, and the rest is the content of the message.
What I am not able to understand is how the client receives the message in a buffer full of bytes and translate it. I know I must use the ntohl (network to host long) function. Both sides use the same architectures.
These are my question:
What is the size I should use for the buffer ?
How to copy the content of the message into another char * [] ?
How to translate from the buffer full of bytes into something I can use ?
How do I use htonl and ntohl ? I need to convert network bytes and write them to a file, how ?
Any code example would more then appreciated...
This is what I wrote in the core so far:
Loop in main
Code:
// Get ready to receive the content of the file
while(received < fileSize ){
// Wait 10 seconds for the next package from the server
if( select(sd+1, &readfd, NULL, NULL, &timeout) != 0 ){
if( read(sd, &buffer, sizeof(buffer)) < 0 ){
perror("Error in reading the package\n")
exit(1);
}
// If first byte is -1 abort
if( atoi(ntohl(buffer[0]) != -1 ){
perror("Error sent from server\n");
exit(1);
}
offset = getOffset(buffer);
lseek(fd, offset, SEEK_SET);
copyMsg(buffer, &temp);
write(fd, temp, sizeof(temp), 0);
}else{
perror("Timeout\n");
exit(1);
}
}
getOffset function
Code:
int getOffset( char * buffer[] ){
static int place=1, i=1, size=0 ;
if( i == 4 ){
return(place);
}
if( (size = atoi(ntohl(buffer[i]))) > 0 ){
place *= size ;
}
i++;
return(getOffset(buffer));
}