Reputation: 2847
I am writing a chatroom that can handle multiple clients. This is my first time programming with sockets and I'm having a bit of trouble understanding how to uniquely identify my sockets. Here is the relevant code:
//set up child processes and allocate shared memory
int numprocesses = 0;
pid_t pids[10];
int shmid;
key_t key = 5678;
int *shm;
if ((shmid = shmget(key, 5000, IPC_CREAT | 0666)) < 0)
{
perror("shmget");
exit(1);
}
shm = (int *) shmat(shmid, NULL, 0);
//initialize shared memory to 0
for (int i = 0; i < 100; i++)
{
*(shm + i) = 0;
}
while(1)
{
//Accepting connections
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
perror("Error on accept");
exit(1);
}
printf("socket: %d\n", newsockfd);
//create a new process to handle each incoming connection
pids[numprocesses] = fork();
//child process
if ((pids[numprocesses] == 0))
{
*(shm + numprocesses) = newsockfd;
close(sockfd);
handle_client(newsockfd, shm);
exit(0);
}
//parent process
{
numprocesses++;
close(newsockfd);
}
}
For some reason every new client that connects to the chatroom has a newsockfd of 4, so I have no idea how to differentiate them. Any help would be greatly appreciate thanks!
Upvotes: 1
Views: 123
Reputation: 70971
Socket descriptors get recycled on a per process base.
accept()
gives you an sd, then you fork-off the client and close the sd in the parent and start over. As the sd had been closed it very well may get used again by the next successful call to accept()
.
As you fork-off a new process for each client, the process-id might be a way to identify a client, at least as long as it is connected and its process is existing.
To historise the connections this (the pid only) may not work as process-ids also might be recycled. So for this case you need to invent some really unique connection id, for example by combining the pid with the timestamp it was created at.
Upvotes: 2