I store my clients like this..
int MAXCLIENTS = 4;
int ClientCount = 0;
int FreeSpot[MAXCLIENTS];
typedef struct CLIENTS_FD{
int sock;
struct sockaddr_in cli_adr;
}cliuse;
cliuse MYCLIENTS[4];
do{
NewSFD = accept(ServerFD,(struct sockaddr *) &cli_addr, &clilen);
if (NewSFD < 0)
{
if (errno != EWOULDBLOCK)
{
perror(" accept() failed");
DCSERVER = TRUE;
}
break;
}
if(ClientCount < MAXCLIENTS){
for(loop = 0; loop < MAXCLIENTS; loop++){
if(FreeSpot[loop]<0){
Clients[loop].sock = NewSFD;
break;
}
}
ClientCount++;
}
else
{
printf("Maximum Client Reached.\n");
char *sendtoclient = "Server full";
send(NewSFD, sendtoclient, strlen(sendtoclient),0);
close(NewSFD);
break;
}
ip = ntohl(cli_addr.sin_addr.s_addr);
printf(" Connection from %d.%d.%d.%d\n",
(int)(ip>>24)&0xff,
(int)(ip>>16)&0xff,
(int)(ip>>8)&0xff,
(int)(ip>>0)&0xff);
dlogs(ip);
}while(NewSFD != -1);
I know i can store my clients file descriptor but how can i store my clients struct and use it afterwards i want to send message to it?.. say i want to send message to client with ip 192.168.5.10.
thanks.
I think you miss some important point about network programming. Maybe you should read this for more details and infos how to start.
Nevertheless
accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)will fill client addres structure which is second parameter (struct sockaddr *addr). You can then easily add this address to your CLIENTS_FD structure.assuming that Clients is cliuse (or
struct CLIENTS_FD).Anyway, like mentioned in some comments above you don’t need to store this address anywhere. All you need to communicate with your client is its
sockfd(which is returned by accept).What is more there could be some bugs in your code:
is uninitialized so when you try to check it
this could lead to wrong behaviour. You could simply write
int FreeSpot[MAXCLIENTS] = {0};You should then somewhere (probably insideif(FreeSpot[loop]<0)statement) add something like thisFreeSpot[loop] = 1;to set it properly before next checks.Since C99 it is possible to declare tables using something else than constant. This is called VLA (variable length array). Nevertheless in your case I can see no point to use VLA. Try
#define MAXCLIENTS 4instead (as suggested in some comment above).To write to the clients, after returning from your do-while loop you can simply use something like below:
where i is number of your client (range 0-3), again assuming that Clients is
cliuse(orstruct CLIENTS_FD).