Home > Net >  problem with the fread on TCP server client
problem with the fread on TCP server client

Time:12-22

I'm building a app TCP server client, i want to send binary to the server/client (so i don't want to use send and recv) and i have a problem, i want to read the file descriptor of my client it's doesn't working i don't understand why because the server accept the client correctly so i have make this function:

bool accept_and_read_client(){
    struct sockaddr_in new_client = { 0 };
    socklen_t length = sizeof(new_client);
    int val_return = accept(sock_fd, (struct sockaddr*)&new_client, &length);
    if(val_return < 0){
        syserr("error of accept");
        return true;
    }
    printf("accept of client successful\n");
    client_array[0].fd = val_return;
    
    size_t nbread;
    client_array[0].file = fdopen(client_array[0].fd, "w ");
    nbread = fread(&val_return, sizeof(char), sizeof(MAX_BUFF), client_array[0].file);
    if(nbread < -1){
        syserr("fread");
        return true;
    }
    printf("number i read : %ld\n", nbread); 
    return false;
}

when i start the server, the server wait client and when i make ./client test the server said:

accept of client successful
fread: Success

so the function fread fails.

on the client.c i do a fwrite like this:

...
FILE* fdc = fdopen(sock_fd, "w ");

    if(fdc == NULL){
        syserr("error of fdopen");
        return 1;
    }
    
    printf("%s\n", argv[1]);
    
    size_t nb_write = fwrite(argv[1], sizeof(*argv), strlen(argv[1]), fdc);
    
    printf("number i write: %ld\n", nb_write);
    
    if(fflush(fdc)){
        syserr("fflush");
    }

if you want to see the client structure:

struct client{
    int fd;
    // char buffer[MAX_BUFF]; 
    FILE* file;
};

struct client client_array[MAX_CLIENTS];

if somebody have a idea why fread don't work tell me please

CodePudding user response:

The fread function probably doesn't fail, instead it's your check that is flawed:

size_t nbread;
...
if(nbread < -1)

The type size_t is unsigned so when you compare nbread with -1 the value -1 will be converted to an unsigned value as well. And that unsigned value will be very large, so nbread will always be smaller than -1.

The fread function will not return -1 or EOF on error, instead it will return a value smaller than the count argument (the third argument). That's the condition you need to check (nbread < sizeof(MAX_BUFF) with the possibly wrong code you currently show).

  • Related