Azures
Azures

Reputation: 56

socket BUFFER TO STRING

I have an issues to convert my BUFFER into a string, I like to know how do I convert my BUFFER, recv from the socket.

I would like to have like my db[0] = buffer, which buffer contain a string like "helloworld", so if i want print db[0], i would get "helloworld".

while(1){
    recv(newSocket, buffer, BUFFER_SIZE, 0);
    if(strcmp(buffer, "q") == 0){
        printf("Deconnexion de %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
        break;
    }else{
        printf("%s\n",buffer);//Client recu: 
        send(newSocket, buffer, strlen(buffer), 0);
        bzero(buffer, sizeof(buffer));

        db[i]=buffer;

        printf("%c",db[i]);

        //mysql_q(db[i]);// query function

        i++;
    }               
}

db type is a char array, but when i compile it gives me this error :

server.cpp:81:12: error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]
  db[i]=buffer;

Upvotes: 1

Views: 931

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136218

You need to process return values of recv and send because they do incomplete reads and writes which must be handled.

Also, recv does not zero terminate received data, you need to do that yourself again to be able to call strcmp.

Most importantly, you need a way to delimit complete messages.

In other words, you need to rewrite the whole piece with message extraction, partial read/write and error handling to make it work.

Upvotes: 3

Jay KM
Jay KM

Reputation: 21

if db[i] is a char array for which db should be double dimension array, you need to do a memcpy or strcpy (if you are sure that buffer will have null terminated string) to get contents of buffer to db[i].

db[i] = buffer

is wrong, thats why compilation error.

Upvotes: 0

Related Questions