0
votes

I am trying to make a TCP Socket Server in C that stores the data that the clients are sending to the server in a struct array. Well, so far, so good. When i am printing the values of the struct, only the last value(key) is stored in all the positions of the struct array! Why is that? Thanks in advance!

Client Code: int main(int argc , char *argv[]) {

int sock;
struct sockaddr_in server;


//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);

char *p;
server.sin_addr.s_addr = inet_addr(argv[1]);
int port = strtol(argv[2], &p, 10);
server.sin_port = htons(port);
server.sin_family = AF_INET;
//Connect to remote server
 if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
    perror("connect failed. Error");
    return 1;
}
write(sock , argv[3] ,strlen(argv[3])+1); //send the 3rd argument(which is the input key)
close(sock);
return 0;
}

Server Code: struct key_store { char *key; }store[1024];

int STORED=0;

void handler(int socket_desc)
{
    int client_sock;
    char client_message[1024];

    client_sock = accept(socket_desc, (struct sockaddr *) NULL, NULL);
    printf("Connection accepted\n");
    while( read(client_sock , client_message , 100) > 0 )
    {
        store[STORED].key=client_message;
        STORED++;
    }
    close(client_sock);
}


int main(int argc , char *argv[])
{   
int socket_desc;
struct sockaddr_in server;

server.sin_port = htons( 8888 );

//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
    printf("Could not create socket");
}
printf("Socket created\n");

//Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;

//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
    //print the error message
    perror("bind failed. Error");
    return 1;
}
printf("bind done\n");

//Listen
listen(socket_desc , 5);

int count =0;
while(count < 3)
{
    handler(socket_desc);
    count++;
}

close(socket_desc);

for (int i=0;i<STORED;i++)
{
    printf("KEY --> %s\n",store[i].key); //print the store keys
}

return 0;
}

Input:

./client 127.0.0.1 8888 123456
./client 127.0.0.1 8888 testkey
./client 127.0.0.1 8888 2017

Output:

./server
Socket created
bind done
Connection accepted
Connection accepted
Connection accepted
KEY --> 2017
KEY --> 2017
KEY --> 2017
1
This line needs to be changed to: store[i].key=strdup(key); Why STORED++? You don't need break statement in for loop.Nguai al
Your problem has nothing to do with sockets, or servers, and not very much to do with structs.user253751

1 Answers

1
votes

you are storing a pointer to client_message in your store. Next message will overwrite that buffer. You have to make a copy of the message before you store it

try

put(strdup(client_message));

You have all sorts of other issues, but this will at least move you forward