Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
int g_portno = 40000;
int main (int argc, char *argv[]){
FILE * error;
error = fopen("server_error.txt","w");
int i;
//Parse command line:
/*if(argc != 2){
printf("Please specify how clients will connect?\n");
exit(0);
}
int num_connections,i;
num_connections = atoi(argv[1]);
printf("num connections: %i\n",num_connections);
*/
//CREATE SOCKET:
int master_socket = socket(AF_INET,SOCK_STREAM,0);
if(master_socket<0){
fprintf(error,"socket create fail\n");
exit(0);
}
//initialize all client_socket[] to 0 so not checked:
int max_clients = 30;
int client_socket[30];
for(i=0;i<max_clients;i++){
client_socket[i] = 0;
}
int opt=1;
if(setsockopt(master_socket,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt))<0){
fprintf(error,"setsockopt fail\n");
exit(0);
}
struct sockaddr_in serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(g_portno);
//BIND:
int bd = bind(master_socket,(struct sockaddr*)&serv_addr, sizeof(serv_addr));
if(bd<0){
fprintf(error,"bind error\n");
exit(0);
}
//LISTEN:
int l = listen(master_socket,10);
if(l<0){
fprintf(error,"listen error");
exit(0);
}
char buffer[1024];
bzero(buffer,1024);
int max_sd,sd,activity,s;
fd_set readfds;
while(1){
//clear the socket set:
FD_ZERO(&readfds);
//add master_socket to set:
FD_SET(master_socket,&readfds);
max_sd = master_socket;
//add child sockets to set:
for(i=0;i<max_clients;i++){
//socket descriptor:
sd = client_socket[i];
//if valid socket desrciptor then add to read list:
if(sd > 0) FD_SET(sd,&readfds);
//highest file descrptor number, need it for the select function:
if(sd > max_sd) max_sd = sd;
}
//wait for an activity on one of the sockets, timeout is NULL, so wait indefinitely.
activity = select(max_sd + 1,&readfds,NULL,NULL,NULL);
if(activity < 0 ){
fprintf(error,"select error\n");
exit(0);
}
//if something happened on the master socket, then its an incoming connection:
if(FD_ISSET(master_socket,&readfds)){
int newsockfd = accept(master_socket, (struct sockaddr*)NULL, NULL);
if(newsockfd<0){
fprintf(error,"accept fail\n");
exit(0);
}
printf("new connection established on fd: %i\n",newsockfd);
//add new socket to array of sockets:
for(i=0;i<max_clients;i++){
if(client_socket[i] == 0){
client_socket[i] = newsockfd;
printf("Adding to list of sockets as: %d\n",i);
break;
}
}
snprintf(buffer,1024,"connected...\n");
send(newsockfd,buffer,strlen(buffer),0);
}
for(i=0;i<max_sd;i++){
if(FD_ISSET(client_socket[i],&readfds)){
snprintf(buffer,1024,"Hello from server client %i\n",i);
s = send(client_socket[i], buffer, strlen(buffer),0);
if(s==-1){
fprintf(error,"send fail\n");
exit(0);
}
}
sleep(1);
}
}
return 0;
}