简体   繁体   中英

C : socket management (socket information is overwritten by newly connected socket)

I'm developing a Chatting program with the multiplexing way by C lang.

My server needs to send a private message from clientA to clientB.

So as you can easily imagine, I recorded the information of the newly connected socket in struct CLIENT

typedef struct client{
char *id;
struct sockaddr_in addr;
int isAlive;}CLIENT;

When new socket is created, I added this info as below:

adr_sz = sizeof(clnt_adr);
clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz);
int newlyAddedConnectedSocket = clnt_sock;
FD_SET(clnt_sock, &reads);
if (fd_max < clnt_sock) {
   fd_max = clnt_sock;
}
printf("newly created connected socket : %d\n",clnt_sock);
str_len = read(clnt_sock, buf, BUF_SIZE);
char idBuf[BUF_SIZE];
buf[str_len] = '\0';

CLIENT newClient;
newClient.id = buf;
newClient.addr = clnt_adr;
newClient.isAlive = TRUE;
clients[clnt_sock] = newClient;
printf("added client id : %s\n",clients[newlyAddedConnectedSocket].id);
for (int k = serv_sock+1; k < fd_max+1; k++) {
  printf("TOTAL CLIENT ID : %s\n",clients[k].id);
}

Above the code, I added some code to check all socket ids currently registered.

But when clientA and clientB are connected, What i got from server is below:

added client id : clientA

TOTAL CLIENT ID : clientA

added client id : clientB

TOTAL CLIENT ID : clientB

TOTAL CLIENT ID : clientB

As you see, the information of clienB overwrites the infromation of clientA.

Is there something I am missing?

If the information is shorted to solve, I will update directly.

Thank you

You're using a pointer to the same buf variable in all your CLIENT entries. This gets overwritten every time you accept a new connection. You need to make a copy of it for each client.

newClient.id = strdup(buf);

And when the client disconnects, you'll need to free this copy with

free(client[clientDisconnecting].id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM