This is the server (sendfile) part:
offset = 0;
for (size_to_send = fsize; size_to_send > 0; ){
rc = sendfile(newsockd, fd, &offset, size_to_send);
if (rc <= 0){
perror("sendfile");
onexit(newsockd, sockd, fd, 3);
}
offset += rc;
size_to_send -= rc;
}
close(fd); /* la chiusura del file va qui altrimenti rischio loop infinito e scrittura all'interno del file */
memset(buffer, 0, sizeof(buffer));
strcpy(buffer, "226 File Successfully transfered\n");
if(send(newsockd, buffer, strlen(buffer), 0) < 0){
perror("Errore durante l'invio 226");
onexit(newsockd, sockd, 0, 2);
}
memset(buffer, 0, sizeof(buffer));
and this is the part of the client (recv file) part:
fsize_tmp = fsize;
sInfo.filebuffer = malloc(fsize);
if(sInfo.filebuffer == NULL){
perror("malloc");
onexit(sockd, 0, fd, 4);
}
while(((uint32_t)total_bytes_read != fsize) && ((nread = read(sockd, sInfo.filebuffer, fsize_tmp)) > 0)){
if(write(fd, sInfo.filebuffer, nread) != nread){
perror("write RETR");
onexit(sockd, 0, 0, 1);
}
total_bytes_read += nread;
fsize_tmp -= nread;
}
close(fd); /* la chiusura del file va qui altrimenti client entra in loop infinito e si scrive all'interno del file */
memset(buffer, 0, sizeof(buffer));
if(recv(sockd, buffer, 34, 0) < 0){
perror("Errore ricezione 226");
onexit(sockd, 0, 0, 1);
}
printf("%s", buffer);
memset(buffer, 0, sizeof(buffer));
memset(dirpath, 0, sizeof(dirpath));
free(sInfo.filebuffer);
The problem is that the string "226 File etc etc" is written inside the file that has been sent.
I've tried to do a small debug and so i've added a printf after the for loop (server sendfile) and a printf after the while loop (client) and i've noticed that the file is sent but on the client it doesn't exit from the while because the printf isn't printed...
Why i got this strange behaviour??br>
EDIT:
The server send the file size to the client whit this code:
fd = open(filename, O_RDONLY);
if(fd < 0){
error!!
}
if(fstat(fd, &fileStat) < 0){
perror("Errore fstat");
onexit(newsockd, sockd, fd, 3);
}
fsize = fileStat.st_size;
if(send(newsockd, &fsize, sizeof(fsize), 0) < 0){
perror("Errore durante l'invio della grandezza del file\n");
onexit(newsockd, sockd, fd, 3);
}
the client receives the fsize from the server with this code:
if(read(sockd, &fsize, sizeof(fsize)) < 0){
perror("Errore durante ricezione grandezza file\n");
onexit(sockd, 0 ,0 ,1);
}
fd = open(sInfo.filename, O_CREAT | O_WRONLY, 0644);
if (fd < 0) {
perror("open");
onexit(sockd, 0 ,0 ,1);
}
fsize_tmp = fsize;
both fsize are declared as uint32_t...
Try this code:
Client side:
/* Client code */
/* TODO : Modify to meet your need */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#define PORT_NUMBER 5000
#define SERVER_ADDRESS "192.168.1.7"
#define FILENAME "/home/toc/foo.c"
int main(int argc, char **argv)
{
int client_socket;
ssize_t len;
struct sockaddr_in remote_addr;
char buffer[BUFSIZ];
int file_size;
FILE *received_file;
int remain_data = 0;
/* Zeroing remote_addr struct */
memset(&remote_addr, 0, sizeof(remote_addr));
/* Construct remote_addr struct */
remote_addr.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_ADDRESS, &(remote_addr.sin_addr));
remote_addr.sin_port = htons(PORT_NUMBER);
/* Create client socket */
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1)
{
fprintf(stderr, "Error creating socket --> %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
/* Connect to the server */
if (connect(client_socket, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "Error on connect --> %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
/* Receiving file size */
recv(client_socket, buffer, BUFSIZ, 0);
file_size = atoi(buffer);
//fprintf(stdout, "\nFile size : %d\n", file_size);
received_file = fopen(FILENAME, "w");
if (received_file == NULL)
{
fprintf(stderr, "Failed to open file foo --> %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
remain_data = file_size;
while ((remain_data > 0) && ((len = recv(client_socket, buffer, BUFSIZ, 0)) > 0))
{
fwrite(buffer, sizeof(char), len, received_file);
remain_data -= len;
fprintf(stdout, "Receive %d bytes and we hope :- %d bytes\n", len, remain_data);
}
fclose(received_file);
close(client_socket);
return 0;
}
Server side:
/* Server code */
/* TODO : Modify to meet your need */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#define PORT_NUMBER 5000
#define SERVER_ADDRESS "192.168.1.7"
#define FILE_TO_SEND "hello.c"
int main(int argc, char **argv)
{
int server_socket;
int peer_socket;
socklen_t sock_len;
ssize_t len;
struct sockaddr_in server_addr;
struct sockaddr_in peer_addr;
int fd;
int sent_bytes = 0;
char file_size[256];
struct stat file_stat;
int offset;
int remain_data;
/* Create server socket */
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1)
{
fprintf(stderr, "Error creating socket --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Zeroing server_addr struct */
memset(&server_addr, 0, sizeof(server_addr));
/* Construct server_addr struct */
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_ADDRESS, &(server_addr.sin_addr));
server_addr.sin_port = htons(PORT_NUMBER);
/* Bind */
if ((bind(server_socket, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))) == -1)
{
fprintf(stderr, "Error on bind --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Listening to incoming connections */
if ((listen(server_socket, 5)) == -1)
{
fprintf(stderr, "Error on listen --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fd = open(FILE_TO_SEND, O_RDONLY);
if (fd == -1)
{
fprintf(stderr, "Error opening file --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Get file stats */
if (fstat(fd, &file_stat) < 0)
{
fprintf(stderr, "Error fstat --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "File Size: \n%d bytes\n", file_stat.st_size);
sock_len = sizeof(struct sockaddr_in);
/* Accepting incoming peers */
peer_socket = accept(server_socket, (struct sockaddr *)&peer_addr, &sock_len);
if (peer_socket == -1)
{
fprintf(stderr, "Error on accept --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "Accept peer --> %s\n", inet_ntoa(peer_addr.sin_addr));
sprintf(file_size, "%d", file_stat.st_size);
/* Sending file size */
len = send(peer_socket, file_size, sizeof(file_size), 0);
if (len < 0)
{
fprintf(stderr, "Error on sending greetings --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "Server sent %d bytes for the size\n", len);
offset = 0;
remain_data = file_stat.st_size;
/* Sending file data */
while (((sent_bytes = sendfile(peer_socket, fd, &offset, BUFSIZ)) > 0) && (remain_data > 0))
{
fprintf(stdout, "1. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data);
remain_data -= sent_bytes;
fprintf(stdout, "2. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data);
}
close(peer_socket);
close(server_socket);
return 0;
}
EDIT : Adding explanation from the man about the offset
The man page of send file said:
If offset is not NULL, then it points to a variable holding the file
offset from which sendfile() will start reading data from in_fd.
When sendfile() returns, this variable will be set to the offset of the byte following the last byte that was read.
The client doesn't know when the file ends. It just reads on until it has received fsize bytes.
In your current implementaton the client will only work for files that are exactly fsize bytes.
I suggest that you change your protocol and add a header that contains the file size.
Why not use the http protocol?
I think you should provide a more detailed code with at least the used variables declarations and initialisation.
How does the client part get the fsize value ?
You should also check the while condition like this :
while(((uint32_t)total_bytes_read < fsize) && ( .....
Don't use "!=", because if (for an unknown reason) total_bytes_read become greater than fsize, you'll be stucked in an infinite loop until the socket connection is closed (and read returns an error).
I also think (but not sure) that you should use recv instead of read in your client part.
You should always determine the size of file you're sending as part of the protocol, for example, you can send the file size as the first 4 (or more, depending on file sizes you expect to handle) bytes, prior to the actual stream.
If you wish to work with constant size files, your implementation should work, in this case please add prints for fsize and total_bytes_read.
You are using the sendfile API incorrectly. Since you are passing in a non-NULL value in the third parameter, sendfile will update the offset for you. But because your send loop is also updating the offset, you will be skipping over some bytes in the case that sendfile was not able to send the whole file in a single call.
From the man page:
If offset is not NULL, then it points to a variable holding the file offset from which sendfile() will start reading data from in_fd. When sendfile() returns, this variable will be set to the offset of the byte following the last byte that was read.
You should remove this line from your send loop:
offset += rc;
Edit: In your update, you use fpl to get the fstat information from your file, but in your sendfile code, you use fd. I would make sure these are what you expect them to be. (This was fixed in yet another update.) In any case, I have written a test program using the code you provided (with my suggested fix), and it seems to work fine with a less than 2KB file and a 3MB file.
Related
I am trying to implement a client-server program in C with TCP for an exercise. The server should be able to serve many clients. The clients asks for some files that the server sends them. Each time the client ends, the server crashes with a segmentation fault error. It prints the "end of service", looking at gdb it also returns to the main function, but it never prints the "prova" after the call to the 'service' function, inside the loop.
Here you can see my server and below my client
/*
* TEMPLATE
*/
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <rpc/xdr.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "../errlib.h"
#include "../sockwrap.h"
#define BUFLEN 1024 /* Buffer length */
char *prog_name;
char *err="-ERR\r\n";
void service(int s);
uint32_t getFileCreationTime(char *filename);
int main (int argc, char *argv[])
{
int conn_request_skt; /* passive socket */
uint16_t lport_n, lport_h; /* port used by server (net/host ord.) */
int bklog = 2; /* listen backlog */
int s; /* connected socket */
socklen_t addrlen;
struct sockaddr_in saddr, caddr; /* server and client addresses */
prog_name = argv[0];
if (argc != 2)
{
printf("Usage: %s <port number>\n", prog_name);
exit(1);
}
/* get server port number */
if (sscanf(argv[1], "%" SCNu16, &lport_h)!=1)
err_sys("Invalid port number");
lport_n = htons(lport_h);
/* create the socket */
printf("creating socket...\n");
s = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
printf("done, socket number %u\n",s);
/* bind the socket to any local IP address */
bzero(&saddr, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = lport_n;
saddr.sin_addr.s_addr = INADDR_ANY;
showAddr("Binding to address", &saddr);
Bind(s, (struct sockaddr *) &saddr, sizeof(saddr));
printf("done.\n");
/* listen */
printf ("Listening at socket %d with backlog = %d \n",s,bklog);
Listen(s, bklog);
printf("done.\n");
conn_request_skt = s;
/* main server loop */
for (;;)
{
printf("loop again\n");
/* accept next connection */
addrlen = sizeof(struct sockaddr_in);
s = Accept(conn_request_skt, (struct sockaddr *) &caddr, &addrlen);
showAddr("Accepted connection from", &caddr);
printf("new socket: %u\n",s);
/* serve the client on socket s */
service(s);
printf("Prova\n");
}
return 0;
}
uint32_t getFileCreationTime(char *filename)
{
struct stat *attr;
stat(filename, attr);
return attr->st_mtime;
}
void service(int s)
{
char rbuf[BUFLEN+1]; /* reception buffer */
char buf[BUFLEN]; /* sending buffer */
char sbuf[BUFLEN]; /* buffer that will contain the dimension of the file */
int n;
char *get, *filename, filename_stats[20];
size_t len;
uint32_t bsent, dimension, modtime;
FILE *fp;
struct stat * fstatus;
for (;;)
{
n=recv(s, rbuf, BUFLEN-1, 0);
if (n < 0)
{
printf("Read error\n");
close(s);
printf("Socket %d closed\n", s);
break;
}
else if (n==0)
{
printf("Connection closed by party on socket %d\n",s);
close(s);
break;
}
else
{
rbuf[n]=0;
get = strtok(rbuf, " ");
filename = strtok(NULL, "\r\n");
if(strcmp(get, "GET") == 0)
{
printf("\nA client requested the file '%s'\n", filename);
fp = fopen(filename, "rb");
if (fp == NULL)
{
printf("-ERR\tCould not open the file\n");
if(writen(s, err, 6) != 6)
printf("Write error\n");
}
fseek (fp, 0, SEEK_END);
dimension = ftell (fp);
//dimension--;
fseek (fp, 0, SEEK_SET);
sprintf(sbuf, "+OK\r\n");
printf("Sending:\n%s\n", sbuf);
if(writen(s, sbuf, 5) != 5)
printf("Write error\n");
//printf("Sending:\n%d\n", dimension);
//dimension = htonl(dimension);
//printf("dimension net=%d\n", dimension);
if(writen(s, &dimension, 4) != 4)
printf("Write error\n");
//dimension = ntohl(dimension);
printf("dimension=%d\n", dimension);
bsent=0;
while(bsent!=dimension)
{
if(dimension-bsent < BUFLEN)
{
//printf("bytes to send <BUFLEN\n");
fread (buf, 1, dimension-bsent, fp);
printf("Sending last %d bytes of the file\n", dimension-bsent);
if(writen(s, buf, dimension-bsent) != dimension-bsent)
printf("Write error\n");
bsent+=dimension-bsent;
}
else
{
//printf("bytes to send > BUFLEN\n");
fread (buf, 1, BUFLEN, fp);
//printf("Sending:\n%s\n", buf);
if(writen(s, buf, BUFLEN) != BUFLEN)
printf("Write error\n");
bsent+=BUFLEN;
printf("Bytes sent: %d\n", bsent);
}
}
fclose (fp);
modtime = getFileCreationTime(filename);
printf("Sending:\n%d\n", modtime);
//modtime = htonl(modtime);
if(writen(s, &modtime, 4) != 4)
printf("Write error\n");
printf("File '%s' correctly sent to the requesting client\n", filename);
}
else //invalid request
{
printf("-ERR\tINVALID REQUEST\n");
if(writen(s, err, 6) != 6)
printf("Write error\n");
}
}
}
printf("End of service\n");
return;
}
And here's the client:
/*
* TEMPLATE
*/
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <rpc/xdr.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "../errlib.h"
#include "../sockwrap.h"
#define BUFLEN 1024 /* Buffer length */
char *prog_name;
int main (int argc, char *argv[])
{
char buf[BUFLEN]; /* transmission buffer */
char rbuf[BUFLEN]; /* receiving buffer */
char ok[5]; /* buffer used to receive the "+OK" message */
uint16_t tport_n, tport_h; /* server port number (net/host ord) */
char **filenames, *out="_out";
FILE* fp;
size_t len;
int s, result, i;
struct sockaddr_in saddr; /* server address structure */
struct in_addr sIPaddr; /* server IP addr. structure */
ssize_t nreadok, nread;
size_t nleft;
uint32_t breceived , bytes, timestamp;
prog_name = argv[0];
if(argc<4)
{
printf("Error! Usage: %s IP_addr port_number filename1 filename2 filename3 ...\n", prog_name);
return -1;
}
filenames = (char **) malloc(argc*sizeof(char*));
for(i=3; i<argc; i++)
{
filenames[i-3] = (char*) malloc (30*sizeof(char));
strcpy(filenames[i-3], argv[i]);
}
/* input IP address and port of server */
result = inet_aton(argv[1], &sIPaddr);
if (!result)
err_quit("Invalid address");
if (sscanf(argv[2], "%" SCNu16, &tport_h)!=1)
err_quit("Invalid port number");
tport_n = htons(tport_h);
/* create the socket */
printf("Creating socket\n");
s = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
printf("done. Socket fd number: %d\n",s);
/* prepare address structure */
bzero(&saddr, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = tport_n;
saddr.sin_addr = sIPaddr;
/* connect */
showAddr("Connecting to target address", &saddr);
Connect(s, (struct sockaddr *) &saddr, sizeof(saddr));
printf("done.\n");
for(i=3; i<argc; i++)
{
//filename=argv[i];
sprintf(buf, "GET %s\r\n", filenames[i-3]); //creating the request "GET filename"
len = strlen(buf);
printf("\n%s", buf);
if(writen(s, buf, len) != len) //sending the request
{
printf("Write error\n");
}
printf("\nwaiting for response...\n");
//filename=argv[i];
//char rbuf[BUFLEN];
nread = readn(s, rbuf, 5); //receiving "+OK\r\n"
if(nread == 0)
printf("Connection closed\n");
if(rbuf[0] == '-')
{
nread = readn(s, rbuf, 1); //remaining byte of the "-ERR\r\n" message
if(nread==0)
printf("Connection closed\n");
printf("-ERROR! The server could not answer the request\n");
close(s);
return -1;
}
bytes=0;
//printf("Bytes 0=%d\n", bytes);
nread = readn(s, &bytes, 4); //receiving the dimension
if(nread == 0)
printf("Connection closed\n");
//printf("Bytes net=%d\n", bytes);
//bytes = ntohl(bytes);
printf("Dimension of the file = %d\n", bytes);
/*
nread = readn(s, rbuf, bytes-1); //receiving the file
if(nread == 0)
printf("Connection closed\n");
*/
strcat(filenames[i-3], "_copy");
fp = fopen(filenames[i-3], "wb"); //creating the file "filename_out"
if (fp == NULL)
{
printf("Could not open the file\n");
}
else
{
//coping data into the copy of the file
breceived=0;
while(1)
{
rbuf[0]=0;
if(bytes-breceived < BUFLEN)
{
//printf("bytes to receive <BUFLEN\n");
printf("Receiving: %d bytes of the file\n", bytes-breceived);
if(readn(s, rbuf, bytes-breceived) != bytes-breceived)
printf("Connection closed\n");
//printf("receiving:\n%s\n", rbuf);
//fputs(rbuf, fp);
fwrite(rbuf, 1, bytes-breceived, fp);
breceived+=bytes-breceived;
printf("Bytes received: %d\n", breceived);
break;
}
else
{
printf("bytes to receive(>BUFLEN) = %d\n", bytes-breceived);
//printf("receiving:\n%s\n", rbuf);
if(readn(s, rbuf, BUFLEN) != BUFLEN)
printf("Connection closed\n");
//printf("receiving:\n%s\n", rbuf);
//fputs(rbuf, fp);
fwrite(rbuf, 1, BUFLEN, fp);
breceived=breceived+BUFLEN;
printf("Bytes received: %d\n", breceived);
}
}
}
if(rbuf[0] == '-')
{
nread = readn(s, rbuf, 1); //remaining byte of the "-ERR\r\n" message
if(nread==0)
printf("Connection closed\n");
printf("-ERROR! The server could not answer the request\n");
close(s);
return -2;
}
//rbuf[bytes]=0;
nread = readn(s, ×tamp, 4); //receiving the timestamp
if(nread == 0)
printf("Connection closed\n");
//timestamp = ntohl(timestamp);
printf("\nFile received: '%s'\t %d bytes \t last mod: %d\n\n", filenames[i-3], bytes, timestamp);
fclose(fp);
}
printf("Closing the connection\n");
close(s);
return 0;
}
Trying to run C executable gives me
Error opening file --> No such file or directory
when the file is clearly there. Does anyone know the cause of this issue? I'm simply compiling a C program using gcc and trying to run the executable. See the following
This is on a
root#EmRtkGps3[~/socket]# ls
serverFile.c sf
root#EmRtkGps3[~/socket]# ./sf
Error opening file --> No such file or directoryroot#EmRtkGps3[~/socket]#
The version of linux I'm running:
Linux EmRtkGps3 3.10.98-poky-edison+ #1 SMP PREEMPT Wed Jul 12 18:30:01 MSK 2017 i686 GNU/Linux
serverFile.c
/* Server code */
/* TODO : Modify to meet your need
from
https://stackoverflow.com/questions/11952898/c-send-and-receive-file
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#define PORT_NUMBER 5000
#define SERVER_ADDRESS "192.168.0.103"
#define FILE_TO_SEND "/home/root/logs/*.UBX"
int main(int argc, char **argv)
{
int server_socket;
int peer_socket;
socklen_t sock_len;
ssize_t len;
struct sockaddr_in server_addr;
struct sockaddr_in peer_addr;
int fd;
int sent_bytes = 0;
char file_size[256];
struct stat file_stat;
off_t offset;
int remain_data;
/* Create server socket */
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1)
{
fprintf(stderr, "Error creating socket --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Zeroing server_addr struct */
memset(&server_addr, 0, sizeof(server_addr));
/* Construct server_addr struct */
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_ADDRESS, &(server_addr.sin_addr));
server_addr.sin_port = htons(PORT_NUMBER);
/* Bind */
if ((bind(server_socket, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))) == -1)
{
fprintf(stderr, "Error on bind --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Listening to incoming connections */
if ((listen(server_socket, 5)) == -1)
{
fprintf(stderr, "Error on listen --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fd = open(FILE_TO_SEND, O_RDONLY);
if (fd == -1)
{
fprintf(stderr, "Error opening file --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Get file stats */
if (fstat(fd, &file_stat) < 0)
{
fprintf(stderr, "Error fstat --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "File Size: \n%d bytes\n", file_stat.st_size);
sock_len = sizeof(struct sockaddr_in);
/* Accepting incoming peers */
peer_socket = accept(server_socket, (struct sockaddr *)&peer_addr, &sock_len);
if (peer_socket == -1)
{
fprintf(stderr, "Error on accept --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "Accept peer --> %s\n", inet_ntoa(peer_addr.sin_addr));
sprintf(file_size, "%d", file_stat.st_size);
/* Sending file size */
len = send(peer_socket, file_size, sizeof(file_size), 0);
if (len < 0)
{
fprintf(stderr, "Error on sending greetings --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "Server sent %d bytes for the size\n", len);
offset = 0;
remain_data = file_stat.st_size;
/* Sending file data */
while (((sent_bytes = sendfile(peer_socket, fd, &offset, BUFSIZ)) > 0) && (remain_data > 0))
{
fprintf(stdout, "1. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data);
remain_data -= sent_bytes;
fprintf(stdout, "2. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data);
}
close(peer_socket);
close(server_socket);
return 0;
}
So I am trying to work on this toy client file server problem.
The iterative version works fine, but when I attempt to fork each new connection in the server code, the client code hangs on the recv call.
I am fairly sure the issue is with the peer_socket, but I have been unable to find my mistake.
It completes just fine if I hit the server with a Ctrl-c though.
CLIENT CODE:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#define PORT_NUMBER 5108
#define SERVER_ADDRESS "localhost"
//#define FILENAME "test.txt"
int main(int argc, char **argv)
{
int client_socket;
ssize_t len;
struct sockaddr_in remote_addr;
char buffer[BUFSIZ];
char filename[256];
char local_filename[256];
int file_size;
FILE *received_file;
int remain_data = 0;
/* Zeroing remote_addr struct */
memset(&remote_addr, 0, sizeof(remote_addr));
memset(local_filename, 0, sizeof(local_filename));
if(argc >1){
strncpy(local_filename, argv[1], 256);
}
/* Construct remote_addr struct */
remote_addr.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_ADDRESS, &(remote_addr.sin_addr));
remote_addr.sin_port = htons(PORT_NUMBER);
/* Create client socket */
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1)
{
fprintf(stderr, "Error creating socket --> %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
//Prompt for file to retrieve
printf("Enter file name: ");
fgets(filename,sizeof(filename),stdin);
printf("Getting file %s", filename);
/* Connect to the server */
if (connect(client_socket, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "Error on connect --> %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
//Send filename to server
/*if(!send(client_socket,filename, sizeof(filename))) {
printf("Error sending filename\n");
exit(EXIT_FAILURE);
}*/
send(client_socket,filename, sizeof(filename),0);
printf("success\n");
/* Receiving file size */
memset(&buffer, 0, sizeof(buffer));
recv(client_socket, buffer, sizeof(buffer), 0);
file_size = atoi(buffer);
fprintf(stdout, "\nFile size : %d\n", file_size);
if(!local_filename[0]) {
received_file = fopen("test2.txt", "w");
}else{
received_file = fopen(local_filename, "w");
}
if (received_file == NULL)
{
fprintf(stderr, "Failed to open file foo --> %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
remain_data = file_size;
//THIS IS THE LOOP THAT HANGS!
while (((len = recv(client_socket, buffer, BUFSIZ, 0)) > 0) && (remain_data > 0))
{
fwrite(buffer, sizeof(char), len, received_file);
remain_data -= len;
fprintf(stdout, "Receive %d bytes and we hope :- %d bytes\n", len, remain_data);
}
printf("did we reach here in the code?\n");
fclose(received_file);
printf("did we reach here in the code?\n");
close(client_socket);
return 0;
}
SERVER CODE:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <signal.h>
#define PORT_NUMBER 5108
#define SERVER_ADDRESS "localhost"
//#define FILE_TO_SEND "hello.c"
int main(int argc, char **argv)
{
int server_socket;
socklen_t global_sock_len;
struct sockaddr_in server_addr;
struct sockaddr_in peer_addr;
/* Create server socket */
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1)
{
fprintf(stderr, "Error creating socket --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Zeroing server_addr struct */
memset(&server_addr, 0, sizeof(server_addr));
/* Construct server_addr struct */
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_ADDRESS, &(server_addr.sin_addr));
server_addr.sin_port = htons(PORT_NUMBER);
/* Bind */
if ((bind(server_socket, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))) == -1)
{
fprintf(stderr, "Error on bind --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Listening to incoming connections */
if ((listen(server_socket, 5)) == -1)
{
fprintf(stderr, "Error on listen --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
//attempt multiple connections via fork
int peer_socket;
int fid;
while(1) {
bool servexit = false;
printf("did we reach HERE in the code?%d\n",getpid());
peer_socket = accept(server_socket, (struct sockaddr *) &peer_addr, &global_sock_len);
//printf("did we reach HERE in the code?\n");
if (peer_socket == -1) {
fprintf(stderr, "Error on accept --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
if((fid = fork()) == -1) {
printf("error\n");
close(peer_socket);
//continue;
}else if(fid > 0){
printf("parent\n");
close(peer_socket);
//continue;
}else if(fid == 0) {
printf("child\n");
socklen_t sock_len;
ssize_t len;
int fd;
int sent_bytes = 0;
char FILE_TO_SEND[256];
char file_size[256];
struct stat file_stat;
off_t offset;
int remain_data;
//int peer_socket = peer_socket;
recv(peer_socket, FILE_TO_SEND, sizeof(FILE_TO_SEND), 0);
printf("Client requested %s", FILE_TO_SEND);
if (strlen(FILE_TO_SEND) > 1) {
strtok(FILE_TO_SEND, "\n");
}
//check for server close command from client
if(strcmp(FILE_TO_SEND,"quit") == 0){
servexit = true;
printf("Quiting server\n");
close(server_socket);
close(peer_socket);
pid_t pid = getppid();
kill(pid, SIGKILL);
exit(0);
}else {
fd = open(FILE_TO_SEND, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Error opening file --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
/* Get file stats */
if (fstat(fd, &file_stat) < 0) {
fprintf(stderr, "Error fstat --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "File Size: \n%d bytes\n", file_stat.st_size);
sock_len = sizeof(struct sockaddr_in);
fprintf(stdout, "Accept peer --> %s\n", inet_ntoa(peer_addr.sin_addr));
sprintf(file_size, "%d", file_stat.st_size);
/* Sending file size */
len = send(peer_socket, file_size, sizeof(file_size), 0);
if (len < 0) {
fprintf(stderr, "Error on sending greetings --> %s", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "Server sent %d bytes for the size\n", len);
//fflush((FILE*)peer_socket);
offset = 0;
remain_data = file_stat.st_size;
/* Sending file data */
while (((sent_bytes = sendfile(peer_socket, fd, &offset, BUFSIZ)) > 0) && (remain_data > 0)) {
fprintf(stdout,
"1. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n",
sent_bytes, offset, remain_data);
remain_data -= sent_bytes;
fprintf(stdout,
"2. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n",
sent_bytes, offset, remain_data);
}
}
break;
}
}
return 0;
}
Ok, so, it turns out that sendfile() doesn't play as nicely as send() in this situation. I found two fixes.
1.) Use send() instead of sendfile()
2.) Retry in both sendfile() (Server) and recv() (client) if either returns -1 (error)
I am trying to write a file transfer program using threading. The format I am trying to follow is:
./server 4501 ..................(will run forever)
./client 4501 add1.txt
./client 4501 bdd1.txt
And add1.txt and bdd1.txt will save in server side as add2.txt and bdd2.txt. But after running my code I found that add2.txt contains the characters from add1.txt plus some extra characters.
**
Updated Solution
**
Server Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <unistd.h>
/* Preprocessor Directives */
#define NTHREADS 50
#define QUEUE_SIZE 5
#define BUFFER_SIZE 256
/* Global counter locked via mutex */
pthread_t threadid[NTHREADS]; // Thread pool
pthread_mutex_t lock;
int counter = 0;
void *threadworker(void *arg)
{
int sockfd, rw; // File descriptor and 'read/write' to socket indicator
char *buffer; // Message buffer
sockfd = (int) arg; // Getting sockfd from void arg passed in
buffer = malloc(BUFFER_SIZE);
bzero(buffer, BUFFER_SIZE);
rw = read(sockfd, buffer, BUFFER_SIZE); // Blocks until there is something to be read in the socket
FILE *fp;
fp=fopen("add2.txt","w");
fprintf(fp,"%s",buffer);
//fwrite(buffer, strlen(buffer) + 1, 1, fp);
//fwrite(buffer,sizeof(char),BUFFER_SIZE, fp);
fclose(fp);
printf("%d\n",strlen(buffer));
printf("the file was received successfully\n");
printf("the new file created is add2.txt\n");
if (rw < 0)
{
perror("Error reading form socket, exiting thread");
pthread_exit(0);
}
//printf("New message received: %s", buffer); // String already has newline
bzero(buffer, BUFFER_SIZE);
//sprintf(buffer, "Acknowledgement from TID:0x%x", pthread_self());
/*rw = write(sockfd, buffer, strlen(buffer));
if (rw < 0)
{
perror("Error writing to socket, exiting thread");
pthread_exit(0);
}*/
/* Critical section */
/*printf("Requesting mutex lock...\n");
pthread_mutex_lock (&lock);
printf("Current counter value: %d, upping by 1...\n", counter);
counter++;
pthread_mutex_unlock (&lock);
printf("Done! Mutex unlocked again, new counter value: %d\n", counter);
*/
close(sockfd);
//printf("TID:0x%x served request, exiting thread\n", pthread_self());
pthread_exit(0);
}
int main(int argc, char *argv[])
{
/* Variable declarations */
int serv_sockfd, new_sockfd; //Socket identifiers for server and incoming clients
struct addrinfo flags; // Params used to establish listening socket
struct addrinfo *host_info; // Resultset for localhost address info, set by getaddrinfo()
socklen_t addr_size; // Client address size since we use sockaddr_storage struct to store
// client info coming in, not using addrinfo as done for host (local)
// by calling getaddrinfo for resolution, which stores results in
// the more convenient addrinfo struct
struct sockaddr_storage client; // Sockaddr storage struct is larger than sockaddr_in,
// can be used both for IPv4 and IPv6
pthread_attr_t attr; // Thread attribute
int i; // Thread iterator
/* Start of main program */
if (argc < 2) {
fprintf(stderr,"Error: no port provided\n");
exit(-1);
}
memset(&flags, 0, sizeof(flags));
flags.ai_family = AF_UNSPEC; // Use IPv4 or IPv6, whichever
flags.ai_socktype = SOCK_STREAM; // TCP
flags.ai_flags = AI_PASSIVE; // Set address for me
if (getaddrinfo(NULL, argv[1], &flags, &host_info) < 0)
{
perror("Couldn't read host info for socket start");
exit(-1);
}
serv_sockfd = socket(host_info->ai_family, host_info->ai_socktype, host_info->ai_protocol);
if (serv_sockfd < 0)
{
perror("Error opening socket");
exit(-1);
}
if (bind(serv_sockfd, host_info->ai_addr, host_info->ai_addrlen) < 0)
{
perror("Error on binding");
exit(-1);
}
freeaddrinfo(host_info); // Don't need this struct anymore
pthread_attr_init(&attr); // Creating thread attributes
pthread_attr_setschedpolicy(&attr, SCHED_FIFO); // FIFO scheduling for threads
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // Don't want threads (particualrly main)
// waiting on each other
listen(serv_sockfd, QUEUE_SIZE); // Pass in socket file descriptor and the size of the backlog queue
// (how many pending connections can be in queue while another request
// is handled)
addr_size = sizeof(client);
i = 0;
while (1)
{
if (i == NTHREADS) // So that we don't access a thread out of bounds of the thread pool
{
i = 0;
}
new_sockfd = accept(serv_sockfd, (struct sockaddr *) &client, &addr_size);
if (new_sockfd < 0)
{
perror("Error on accept");
exit(-1);
}
pthread_create(&threadid[i++], &attr, &threadworker, (void *) new_sockfd);
sleep(0); // Giving threads some CPU time
}
return 0;
}
And the Client Code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <unistd.h>
#define BUFFER_SIZE 256
int main(int argc, char *argv[])
{
int sockfd, rw;
struct addrinfo flags;
struct addrinfo *server_info;
char *buffer = malloc(BUFFER_SIZE);
if (argc < 4)
{
fprintf(stderr, "Usage: ./client <hostname/address> <port> <file_path>");
exit(-1);
}
memset(&flags, 0, sizeof(flags)); // Clear so we're not working with garbage
flags.ai_family = AF_UNSPEC; // IPv4 or IPv6 doesn't matter
flags.ai_socktype = SOCK_STREAM; // TCP
flags.ai_flags = AI_PASSIVE; // get the IP for me
if (getaddrinfo(argv[1], argv[2], &flags, &server_info) < 0) { // Resolve host based on CMD args
perror("Couldn't find host");
exit(-1);
}
sockfd = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol); // Initialize socket
if (connect(sockfd, server_info->ai_addr, server_info->ai_addrlen) < 0)
{
perror("Couldn't conenct...");
exit(-1);
}
//printf("Connection established, please enter a message:\n");
bzero(buffer, BUFFER_SIZE);
//fgets(buffer, BUFFER_SIZE - 1, stdin);
//char buffer[100];
FILE *f;
size_t read=0;
if((f=fopen(argv[3],"r"))==NULL){
printf("Failed");
exit(-1);
}
//fseek(f, 0, SEEK_END);
//len = ftell(f);
//while (fgets(buffer, strlen(buffer), f) != NULL)
//fscanf(f,"%s",buffer);
//fread(buffer, strlen(buffer)+1, 1, f);
do{
read = fread(buffer,sizeof(char),BUFFER_SIZE-1, f);
if (read > 0) //if return value is > 0
{
buffer[BUFFER_SIZE]='\0';
rw = write(sockfd, buffer, strlen(buffer));
}
}
while(read == BUFFER_SIZE); //end when a read returned fewer items
fclose(f);
//write(sock, &len, sizeof(int));
//write(sock, buffer, len);
printf("the file was sent successfully");
//rw = write(sockfd, buffer, strlen(buffer)); // Sending the contents of the buffer - writes using socket file descriptor
if (rw < 0)
{
perror("Failed to send message");
exit(-1);
}
/*bzero(buffer, BUFFER_SIZE);
rw = read(sockfd, buffer, BUFFER_SIZE); // Read the ENTIRE buffer because we don't know stlen yet
if (rw < 0)
{
perror("Error reading from socket");
exit(-1);
}
printf("The message is: %s\n", buffer);
*/
close(sockfd);
return 0;
}
My add1.txt file contains
abcd
efgh
ijkl
mnop
The add2.txt file contains as output:
abcd
efgh
ijkl
mnop
############################################################################################################################################################################################################################################
Can anyone please advice me what are the modifications I will need then.
Thank you, in advance.
You need to call fclose on File *fp (server code) and File *f (client code) after you are done reading/writing the file. You did close the connection between the client and server, but you did not close the file stream which is probably the cause of the files being empty. So in your case it will be safe to call fclose after you called fprintf (server code) and fscanf (client code).
This is a snippet of client.c:
size_t fsize;
int total_bytes_read = 0, ret_val;
hp = gethostbyname(argv[1]);
DescrittoreClient = socket(AF_INET, SOCK_STREAM, 0);
connect(DescrittoreClient, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
strcpy(Buffer, filename);
send(DescrittoreClient, Buffer, strlen(Buffer), 0);
ret_val = read(DescrittoreClient, &fsize, sizeof(fsize));
if(ret_val == -1){
printf("Errore durante ricezione grandezza file\n");
close(DescrittoreClient);
exit(1);
}
fd = open(filename, O_CREAT | O_WRONLY,0644);
if (fd < 0) {
perror("open");
exit(1);
}
while(total_bytes_read < fsize){
while ((nread = read(DescrittoreClient, Buffer, sizeof(Buffer))) > 0){
write(fd, Buffer, nread);
total_bytes_read += nread;
}
}
printf("File ricevuto\n");
And this is a snippet of server.c:
int DescrittoreServer, DescrittoreClient, LunghezzaClient;
int NumPorta = atoi(argv[1]);
char Buffer[1024] = {};
int rc, fd;
off_t offset = 0;
struct stat stat_buf;
char filename[1024] = {};
int fsize[10240] = {};
DescrittoreServer = socket(AF_INET, SOCK_STREAM, 0);
if(bind(DescrittoreServer, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
perror("Errore di bind\n");
close(DescrittoreServer);
exit(1);
}
listen(DescrittoreServer, 5);
LunghezzaClient = sizeof(cli_addr);
while(1){
DescrittoreClient = accept(DescrittoreServer, (struct sockaddr *) &cli_addr, &LunghezzaClient);
rc = recv(DescrittoreClient, filename, sizeof(filename), 0);
fprintf(stderr, "Ricevuta richiesta di inviare il file: '%s'\n", filename);
/* open the file to be sent */
fd = open(filename, O_RDONLY);
/* get the size of the file to be sent */
fstat(fd, &stat_buf);
*fsize = stat_buf.st_size;
send(DescrittoreClient, fsize, sizeof(fsize), 0);
/* copy file using sendfile */
offset = 0;
rc = sendfile(DescrittoreClient, fd, &offset, stat_buf.st_size);
if (rc != stat_buf.st_size) {
fprintf(stderr, "Trasferimento incompleto: %d di %d bytes\n", rc, (int)stat_buf.st_size);
exit(1);
}
close(DescrittoreClient);
close(fd);
}
What does this code do:
1) client sends the name of a file
2) server sends the length (in byte) of the file
3) client receives the length of the file
4) server sends the file
5) client receives the file
The problem is that the file is not entirely received but only a part of it is written by the client (for example a file of 2143 byte is sent by the server and only 95 byte are received by the client) and i don't understand why!
PS: some errors handling have been deleted so the code is more readable!
You have to call recv() in a loop and sum up it's return values:
while (read_bytes < filesize) {
read_bytes += recv(socket, buffer + read_bytes, filesize-read_bytes, flags)
}
of course you should also add error handling, i.e., check if you read 0 bytes and the connection was closed.
The problem is that i have declared char nread=0 instead of int nread=0 into the client and so the maximum value i can read with char is 127...changed char to int solved my problem!