Pages

Subscribe:

Ads 468x60px

Showing posts with label gcc. Show all posts
Showing posts with label gcc. Show all posts

Saturday, February 9, 2013

Non Blocking I/O using SELECT System Call in Linux

Today we are going to explore a very important system call in Linux, The Select system call. Select System call is use  when we need non blocking executions. The use of the select can be explained via an example code. Lets assume that we use a socket program with a server and few client programs. To accept and read from clients what will be your normal approach?.. Probably you are checking for new clients and the data from the existing clients and probably use a read system call. Here  the approach is blocking, the program is blocked for events. But using the select system call, it can be achieved in a non- blocking manner. Here we put the connected clients along with the server into a fd_set type variable. Then the select system  call is looking for any read events for each clients and read the data non bloc-kingly.

Lets see an example code for this scenario.

In this example there is a server which is binded to port 9999. and clients can be connected to that port. Then the server identify whether a new client or data from an existing  client. Select call will monitor the read_fds and act immediately for a change of a read file descriptor. There is a time out value for select system call.

In this example many clients are connected to the server and heart beats are send for the clients for every 3 seconds. And from the server we can send work(In this scenario messages) for clients. Then the clients work on those messages and send result to the server. We can non- bloc-kingly send data to clients and read data from clients using the select system call. :) 

Server.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>
#include <time.h> 
#include "Data.h"

#define PORT "9999"   // port we're listening on
#define MAX_MESSAGE_SIZE 50 // Maximum message size

pthread_mutex_t mutexSync = PTHREAD_MUTEX_INITIALIZER;

int signal =0;
char Buffer[1024];

int Initialize(void);
void *Communicate(void *);
void *get_in_addr(struct sockaddr *sa);
void AcceptNewClients(fd_set &master , int &fdmax ,int listener);
void AcceptDataFromClients(int iClient , fd_set & master);
void SendHeartBeats(int iListener , int iClient);
void SendWorkForClients( int fdmax , int iListener , int iClient , int &signal);



//****************************************************************************************************
int main(void)
{
	pthread_t t;
	// char Buffer[256];
	int iListenSockId = Initialize();
	//Communicate(&iListenSockId);
	pthread_create(&t , NULL, Communicate , (void *)&iListenSockId); 
	while(1)
	{
		printf("Enter a message to Send :: ");
		fgets(Buffer , 255 , stdin);
		pthread_mutex_lock(&mutexSync);
		signal++;
		//printf("Message is %s %d \n", Buffer , signal);
		pthread_mutex_unlock(&mutexSync);
		sleep(1);
		//memset(&Buffer[0], 0, sizeof(Buffer));
			
	}
	
    return 0;
}

//****************************************************************************************************
int Initialize()
{
	int listener ;     // listening socket descriptor
	int rv ;
	struct addrinfo hints, *ai, *p;
	int yes=1;        // for setsockopt() 
	 // get us a socket and bind it
    
	memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0) 
	{
        fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));
        exit(1);
    }
    
    for(p = ai; p != NULL; p = p->ai_next) 
	{
        listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (listener < 0) 
		{ 
            continue;
        }       
        // lose the pesky "address already in use" error message
        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
        if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) 
		{
            close(listener);
            continue;
        }
        break;
    }
    // if we got here, it means we didn't get bound
    if (p == NULL) 
	{
        fprintf(stderr, "selectserver: failed to bind\n");
        exit(2);
    }
    freeaddrinfo(ai); // all done with this
    // listen
    if (listen(listener, 10) == -1) {
        perror("listen");
        exit(3);
    }
	
	return listener;

}

//****************************************************************************************************
void * Communicate(void * id)
{
	int *iSockID = (int *) id;
	int listener =  *iSockID;

    fd_set master;    // master file descriptor list
    fd_set read_fds;  // temp file descriptor list for select() read
    int fdmax;        // maximum file descriptor number

    int i, j, rv;

    FD_ZERO(&master);    // clear the master and temp sets
    FD_ZERO(&read_fds);
    // add the listener to the master set
    FD_SET(listener, &master);
	printf("Listener is %d \n" , listener);

    // keep track of the biggest file descriptor
    fdmax = listener; // so far, it's this one
	//accept 3 clients

	
    // main loop
    for(;;) {
		memcpy(&read_fds , &master , sizeof(master));
		struct timeval tv;
		tv.tv_sec = 3;
		tv.tv_usec = 0;
		int iResult = select(fdmax+1, &read_fds, NULL, NULL, &tv) ;
        if (iResult == -1) 
		{
            perror("select");
            exit(4);
        }
	
		// ADD NEW CONNECTIONS READ FROM CONNECTIONS	
		for(i = 0; i <= fdmax; i++)
		{			   
            if (FD_ISSET(i, &read_fds)) 
			{			
				if (i == listener) 
				{                                    
					AcceptNewClients(master , fdmax , listener );	
                } else 
				{
					AcceptDataFromClients(i , master);
                } 
            } 

			
        } 
        for(i = 0; i <= fdmax; i++) 
		{			
			//send work for clients
			SendWorkForClients(fdmax , listener , i , signal);
			//sending heart beats
		   	SendHeartBeats(listener , i );
		}

    } 
	return 0;
}

//****************************************************************************************************
void SendWorkForClients(int fdmax , int iListener , int iClient , int &signal)
{

		if(signal == 1 && iClient != iListener && iClient > iListener)
		{
			//send data to some client;
			//printf("data send to CLIENT DUMMY \n");
			//signal--;
			ServerData * data = new ServerData();
			data->iType = 2;
			strcpy(data->cMessage , Buffer );
			int numbytes  = write( iClient , data ,sizeof(*data));
			printf("Number of bytes written :: %d ID :: %d  \n" , numbytes , iClient);
		
			delete data;
		}
		if(signal == 1 && iClient != iListener && iClient > iListener && iClient == fdmax)
		{
			pthread_mutex_lock(&mutexSync);
			signal--;
			pthread_mutex_unlock(&mutexSync);
		}
	
}

//****************************************************************************************************
void SendHeartBeats(int iListener , int iClient)
{
	ServerData * data = new ServerData();
	time_t rawtime;
	time ( &rawtime );

	data->iType = 1;
	strcpy(data->cMessage , ctime (&rawtime)  );
	//char cHeartBeat []  = "HEARTBEAT";


		if(iClient!= iListener && iClient > iListener){
			int numbytes  = write( iClient , data , sizeof(*data)); 
			//printf("Number of bytes written :: %d ID :: %d  \n" , numbytes , i);
		}					
	
	delete data;
}
//****************************************************************************************************
void AcceptNewClients(fd_set&  master , int& fdmax ,int listener)
{
		socklen_t addrlen;
		struct sockaddr_storage remoteaddr; // client address
		char remoteIP[INET6_ADDRSTRLEN];		
		int newfd;        // newly accept()ed socket descriptor
		addrlen = sizeof(remoteaddr);
		ServerData * data = new ServerData();
		data->iType = 2;
		strcpy(data->cMessage , "SERVER MESSAGE :: ACCEPTED" );
        newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen);
		write(newfd , data , sizeof(*data));
		if (newfd == -1) 
		{
            perror("accept");
        }else 
		{
            FD_SET(newfd, &master); // add to master set
            if (newfd > fdmax) 
			{    // keep track of the max
				fdmax = newfd;
            }
            printf("selectserver: new connection from %s on socket %d\n", inet_ntop(remoteaddr.ss_family,
                                get_in_addr((struct sockaddr*)&remoteaddr), remoteIP, INET6_ADDRSTRLEN), newfd);
        } 
		
		delete data;
}

//****************************************************************************************************
void AcceptDataFromClients(int iClient , fd_set& master)
{
	char buf[1024];    // buffer for client data
	int nbytes;
	
	nbytes = recv(iClient, buf, sizeof buf, 0);
	//printf("DISCONNECTING  %d \n", nbytes);
    if (nbytes <= 0) 
	{
    // got error or connection closed by client
		if (nbytes == 0) 
		{
			// connection closed
			printf("selectserver: socket %d hung up\n", iClient);
		} else 
		{
			perror("recv");
		}
        close(iClient); // bye!
        FD_CLR(iClient, &master); // remove from master set
    } else 
	{
    // we got some data from a client
		printf("CLIENT DATA :: %s",buf);
                       
    }

}

//****************************************************************************************************
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET) 
	{
        return &(((struct sockaddr_in*)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

Client.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include "Data.h"


int main(int argc , char * argv [])
{
	int SockFD , PortNo , n , fdmax ,nbytes;
	struct sockaddr_in Server_Address;
	struct hostent *Server;
	fd_set master;    // master file descriptor list
    fd_set read_fds;  // temp file descriptor list for select()
	FD_ZERO(&master);    // clear the master and temp sets
    FD_ZERO(&read_fds);

	char Buffer[1024];
	memset(Buffer, 0, sizeof(Buffer));

	if(argc < 3)
	{
		printf("Error hostname port required \n");
		exit(0);
	}

	PortNo = atoi(argv[2]);

	// create a socket	
	SockFD =  socket(AF_INET , SOCK_STREAM , 0);

	if(SockFD < 0 )
	{
		perror("Error Creating Socket");
		exit(1);
	}
	
	Server = (struct hostent *) gethostbyname(argv[1]);
	if(Server == NULL)
	{
		printf("Error :: No Such Host \n");
		exit(0);
	}

	bzero((char *) &Server_Address , sizeof(Server_Address));
	Server_Address.sin_family =  AF_INET;
	bcopy((char *) Server->h_addr , (char *) &Server_Address.sin_addr.s_addr , Server->h_length);
	
	Server_Address.sin_port = htons(PortNo);
	
	//connect to the server
	int listener = connect(SockFD , (struct sockaddr *) &Server_Address , sizeof(Server_Address));
	if( listener < 0)
	{
		perror("Error Connecting \n");
		exit(1);
	}
	

	while(1)
	{	
		n = read(SockFD , Buffer , sizeof(Buffer));
		ServerData * data = new ServerData();
		data = (ServerData *) Buffer;
		
		if(n <= 0)
		{
			perror("Error receiving data \n");
			exit(1);
		}
		//int result = strcmp( Buffer, "HEARTBEAT" );
		if(data->iType == 2)
		{
			//sleep(1);	
			printf("Received :: %s", data->cMessage);
			write(SockFD , "CLIENT MESSAGE-->ACCEPTED" ,26);
		}	
		else if(data->iType == 1 )
		{
			//sleep(2);	
			printf("Heart Beating Server::  %s", data->cMessage);
		}
		memset(Buffer, 0, sizeof(Buffer));
		//
		
	}

	return 0;

}

Data.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Header file for data
// type 1 -> Heart Beat Message
// type 2 -> Server Task Message

class ServerData
{
	public:
	int iType;
	char cMessage [50];
};

To compile and run the server...

1
2
3
g++ Select.cpp -lpthread

./a.out

To compile and run the client...

1
2
3
g++ -o client client.cpp

./client localhost 9999


That's it folks. If you have anything to clarify just put a comment. I'll answer for the best of my knowledge.

Here is a nice tutorial for Linux system calls. I recommend you all to read it.
http://www.beej.us/guide/bgnet/output/html/multipage/index.html


Wednesday, January 23, 2013

Producer Consumer Problem in C++

Today I'm going to solve a most common problem which is known as the consumer producer problem. In this context we have a shared buffer which the producers produce and the consumers consume. The consumers and producers are threads which will simultaneously produce and consume. There are some conditions to be met where consumers have to wait until producers produce, and another thing is that when the buffer is full producers must halt until the consumers consume.

In the following example was implemented using pthreads. The producer produce a random number to the buffer and consumers consume that number. Mutex locks are used to protect the shared buffer. 
ProducerConsumer.cpp     DOWNLOAD SOURCE

#include <iostream>
#include <pthread.h>
#include <vector>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>



#define BUFFER_SIZE 10

void InitializeData();
void *Produce(void *);
void *Consume(void *);
int InsertItem(int);
int RemoveItem(int *);

int iCounter;
pthread_mutex_t mutex;
sem_t full, empty;

int buffer[BUFFER_SIZE];



int main(int argc , char * argv[])
{
 InitializeData(); 
 pthread_t ProducerThread , ConsumerThread;
 int *aa = new int [10];
 for(int i = 0 ; i < 10 ; i++)
 {
  aa[i] = i;
  pthread_t t;
  pthread_create(&t , NULL, Produce , &aa[i]);
  printf("Creating Producer %d \n", i);
 }
 int *bb = new int[10];
 for(int i = 0 ; i < 10 ; i++)
 {
  bb[i] = i;
  pthread_t t;
  pthread_create(&t , NULL, Consume , &bb[i]);
  printf("Creating Consumer %d \n", i);
 }
 
 sleep(5);
 delete [] aa;
 delete [] bb;
 

 return 0;
}

//****************************************************************************************************
void InitializeData()
{
 pthread_mutex_init(&mutex , NULL);
 sem_init(&full , 0 ,0);
 sem_init(&empty , 0 , BUFFER_SIZE);
 
 iCounter = 0;
 

}

//****************************************************************************************************
void * Produce(void * Param)
{
 int item;
 
 while(1)
 {
  //sleep(1);
  item = rand() % 100;
  sem_wait(&empty);
  pthread_mutex_lock(&mutex);
  int iMsg = InsertItem(item);
  
  if(iMsg == -1){
   printf("Error Inserting Item \n");
  }else
  {
   printf("Produced Item :: %d  Thread No :: %d\n", item , *((int *)Param));
  }
  pthread_mutex_unlock(&mutex);
  sem_post(&full);
  
 }
}

//****************************************************************************************************
void * Consume(void * Param)
{
 int item;
 
 while(1)
 {
  //sleep(1);
  sem_wait(&full);
  pthread_mutex_lock(&mutex);
  int iMsg = RemoveItem(&item);
  
  if(iMsg == -1){
   printf("Error Removing Item \n");
  }else
  {
   printf("Consumed Item :: %d  Thread No :: %d \n", item ,*((int *)Param));
  }
  pthread_mutex_unlock(&mutex);
  sem_post(&empty);
  
 }
}

//****************************************************************************************************
int InsertItem(int item)
{
 if(iCounter < BUFFER_SIZE)
 {
  buffer[iCounter] =  item;
  iCounter++;
  return 1;
 }
 else{
  return -1;
 }

}

//****************************************************************************************************
int RemoveItem(int *item)
{
 if(iCounter > 0)
 {
  *item = buffer[iCounter - 1];
  iCounter--;
  return 1;
 }
 else{
  return -1;
 }
}

That's it folks. Hope to see you soon in another exciting tutorial.

Friday, January 18, 2013

How to send Complex Data Structures in a Socket Program

Hi all, Hope you guys are doing well. I was busy with my work last few days. Today I'm going to write a post about sending Complex data structures using a socket program. In this post I assume that you are somewhat familiar with the socket programming basics.

In the following example we are creating a Object type in the server program and send that to the client program. This is a simple serialize and deserialize mechanism to send complex data structures through a socket program using only the STL library. If you want more complex and complete functionality you might try the boost library. 

Here we are going to send the following data structure.
 Data.h File
class InnerData{
    public:
    int c;
};

class Data{
    public:
    int a;
    char b[20];
    InnerData id;
  
};

Now we write the Server program which will create a socket, bind that socket to a port and listen for incoming connections. If there is a incoming connection accept the connection, serialize the data send to the connected client.

Server.cpp File
#include <stdio.h>
#include <cstdlib> 
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <arpa/inet.h> 
#include "Data.h"

int main(int argc , char * argv [])
{
    int SockFD , NewSockFD , PortNo, Clilen;
    char Buffer[1024];
 struct sockaddr_in Server_Addr , Cli_Addr;
 int n , pID;

 //create a socket
 SockFD =  socket(AF_INET , SOCK_STREAM , 0);
 if(SockFD < 0)
 {
  perror("Error Creating Socket \n");
  exit(1);
 }
 std::cout << "Socket Created..." << std::endl;

 bzero((char *) &Server_Addr , sizeof(Server_Addr));
 PortNo = atoi(argv[1]);
 Server_Addr.sin_family = AF_INET;
 Server_Addr.sin_addr.s_addr = INADDR_ANY;
 Server_Addr.sin_port = htons(PortNo);

 
 //bind the socket
 if(bind(SockFD , (struct sockaddr *) &Server_Addr , sizeof(Server_Addr)) < 0)
 {
  perror("Error Binding \n");
  exit(1);
 }
 std::cout << "Socket Binded..." << std::endl;
 //listen for incoming clients
 listen(SockFD , 5);
 Clilen =  sizeof(Cli_Addr);
 std::cout << "Waiting For Connections..." << std::endl;
 
 while(1)
 {
  //accept a client 
  NewSockFD = accept(SockFD , (struct sockaddr *) &Cli_Addr ,(socklen_t *) &Clilen);
  printf("New Client %d \n", NewSockFD);
  if(NewSockFD < 0)
  {
   perror("Error accepting \n");
   exit(1);
  }  
   bzero(Buffer , 1024);
   printf("New Client Connected, Process ID :: %d \n",pID);
   //create the Data
   Data *data = new Data();
   data->a = 23232;
   strcpy(data->b , "TEST MESSAGE" );
   data->id.c =1000;
  
   n =  write(NewSockFD , data ,sizeof(*data) );
   if(n < 0)
   {
    perror(" Error Sending Message \n");
    exit(1);
   }
  
 }
 return 0;
}

Now the client accept the data send by the client and deserialize it.

Client.cpp
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h> 
#include "Data.h"


int main(int argc , char * argv [])
{
 int SockFD , PortNo , n;
 struct sockaddr_in Server_Address;
 struct hostent *Server;
 
 char Buffer[1024]; // Buffer to read data

 if(argc < 3)
 {
  printf("Error hostname port required \n");
  exit(0);
 }
 PortNo = atoi(argv[2]);
 // create a socket 
 SockFD =  socket(AF_INET , SOCK_STREAM , 0);

 if(SockFD < 0 )
 {
  perror("Error Creating Socket");
  exit(1);
 }
 
 Server = (struct hostent *) gethostbyname(argv[1]);
 if(Server == NULL)
 {
  printf("Error :: No Such Host \n");
  exit(0);
 }

 bzero((char *) &Server_Address , sizeof(Server_Address));
 Server_Address.sin_family =  AF_INET;
 bcopy((char *) Server->h_addr , (char *) &Server_Address.sin_addr.s_addr , Server->h_length);
 
 Server_Address.sin_port = htons(PortNo);
 
 //connect to the server
 if(connect(SockFD , (struct sockaddr *) &Server_Address , sizeof(Server_Address)) < 0)
 {
  perror("Error Connecting \n");
  exit(1);
 }
 Data * data = new Data();
 n = read(SockFD , Buffer , sizeof(Data));
 data = (Data *) Buffer;
 printf("Read Size %d \n" , n);
 if(n < 0)
 {
  perror("Error receiving data \n");
  exit(1);
 }
 printf("Received :: ID :: %d  MESSAGE :: %s Complex ID:: %d \n", data->a , data->b ,data->id.c );
 bzero(Buffer , 1024);

 return 0;

}

First we compile the Server.cpp file
g++ -o Server Server.cpp

Then we run the server giving the port as an argument.
./Server  7788

Then compile and run the client program using a new terminal.
g++ -o Client Client.cpp

./Client localhost 7788

That's it folks. It's a simple approach. But solve the problem. Remember that this only works since we are using the same computer architecture. If you are using different architectures you have to consider about the endian problem also.. :)

Friday, November 30, 2012

How to write a Simple Web Server using C

In this post I'm going to explain how to write a simple but functional web server using sockets. First we have to set configuration for our web server and most common way of doing is to put the configurations into a .ini file. I used inih which is a simple .ini parser written in C. source 

Below is a sample .ini file
; Config file for ASK server

[Protocol]             
Version=6              ; IPv6

[Web]
http_version=HTTP/1.1
root_dir = www/
default_page = index.html
error_page = error.html
backlog = 10
max_header_size=1024

[Codes]
200 = OK
404 = Content Not Found

Below is the  askserver.c source file.  First the configurations are loaded and waiting for incoming requests. Then whenever a request is arrived the server check for the file requested. If it is available send a message code 200 and the file type server is going to send to the client. If the requested file was not fond, then send the message code 400 content not found. 
When a available file is send to the client, method is used.

sendfile(destination, source, offset,size);

//******************** askserver.c ******************/
// Aruna Sujith Karunarathna
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netinet/tcp.h>
#include <limits.h>
#include <unistd.h>
#include <assert.h>
#include "ini.h"

#define CONFIGURATION_FILE  "configuration/ask.ini"


typedef struct{
    int version;
    int backlog;
	int max_header_size;
    const char* http_version;
    const char* root_dir;
	const char* default_page;
	const char* error_page;
} configuration;
configuration config;

void sigchld_handler(int s){
	while(waitpid(-1, NULL, WNOHANG) > 0);
}

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa){
	if (sa->sa_family == AF_INET) {
		return &(((struct sockaddr_in*)sa)->sin_addr);
	}
	return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

static int handler(void* user, const char* section, const char* name,const char* value){
    
    configuration* pconfig = (configuration*)user;

    #define MATCH(s, n) strcasecmp(section, s) == 0 && strcasecmp(name, n) == 0
    if (MATCH("protocol", "version")) {
        pconfig->version = atoi(value);   
    } else if (MATCH("web", "http_version")) {
        pconfig->http_version = strdup(value);
    } else if (MATCH("web", "root_dir")) {
        pconfig->root_dir = strdup(value);
    } else if (MATCH("web", "default_page")) {
        pconfig->default_page = strdup(value);
    } else if (MATCH("web", "error_page")) {
        pconfig->error_page = strdup(value);
    } else if (MATCH("web", "backlog")) {
        pconfig->backlog = atoi(value);
    } else if (MATCH("web", "max_header_size")) {
        pconfig->max_header_size = atoi(value);
    } else {
        return 0;  /* unknown section/name, error */
    }
    return 1;
}

char* get_extension(char* file_name){
    char* extension;
    extension = strchr(file_name,'.')+1	; 
    printf("EXTENSION %s \n",extension);
    return extension;
}

char* get_content_type(char* extension){
    char* type;
    if(strcmp(extension,"html")==0)
        type = "text/html";
    else if(strcmp(extension,"css")==0)
        type = "text/css";
    else if(strcmp(extension,"txt")==0)
        type = "application/text";
    else if(strcmp(extension,"pdf")==0)
        type = "application/pdf";
    else if(strcmp(extension,"zip")==0)
        type = "application/zip";    
    else if(strcmp(extension,"xml")==0)
        type = "application/xml";  
    else if(strcmp(extension,"js")==0)
        type = "application/javascript";                  
    else if(strcmp(extension,"jpg")==0)
        type = "image/jpg";
    else if(strcmp(extension,"png")==0)
        type = "image/png";    
    else if(strcmp(extension,"exe")==0)
        type = "application/octet-stream";
    else if(strcmp(extension,"ico")==0)
        type = "image/x-icon";
    else if(strcmp(extension,"php")==0)
        type = "text/html";
        
    printf("TYPE %s ",type);    
    return type;    

}

int set_header(char *header,int status_code,char *file_name,int file_length){
    if(status_code==404){
        //printf("%s %d File Not Found\n",config.http_version,status_code);
        sprintf(header, 
				"%s %d File Not Found\n"					
		     	 "\n",config.http_version,status_code);
		printf("\nHEADER MESSAGE %s \n",header);
        return -1;
    }
	if(status_code==400){
		sprintf(header, 
				"%s %d Bad Request\n"					
		     	 "\n",config.http_version,status_code);
		return -1;
	}
	if(status_code==501){	
		sprintf(header,"%s %d POST Not Implemented\n "
		"\n POST Not Implemented",config.http_version,status_code);	
		return -1;
	}
	char *extension;
	extension = get_extension(file_name);     
	char *content_type;
	content_type = get_content_type(extension);
		
	sprintf(header,"%s %d OK \n"	
	"Content-Type: %s\n"
	"Content-Length: %i\n"
		      "\n",config.http_version,status_code,content_type ,file_length);
	printf("\nHEADER MESSAGE %s \n",header);	      
}

char* check_request(char * request){
	char* ptr;
	ptr = strstr(request," HTTP/");
   // printf("CHK REQUEST %s \n",request);
	if(ptr == NULL)	{
		printf("Not HTTP request\n");
	}else{
	 /* *** HTTP request received *** */

		/* *** check for GET request *** */
		if(strncmp(request,"GET ",4) == 0)	{
			ptr="GET";
		}
		/* *** check for POST request, give 501 error if received *** */
		else if(strncmp(request,"POST ",5) == 0){
			printf("501 Method not implemented\n");
			ptr="POST";
		}
	}

	return ptr; 
}

char* get_path(char *request)
{
	int i=0;
//	printf("REQUEST %s \n",request);
	char *token = NULL;
	token = strtok(request, " ");
	token = strtok(NULL, " ");
	
	return token;
}

int send_content(char* file_name, int socket, int status_code){
    int sent_size; 	
    char header[config.max_header_size];
	int open_file;               /* file descriptor for source file */
    struct stat stat_buf;  /* hold information about input file */
    off_t offset = 0;      /* byte offset used by sendfile */
    int return_code;                /* return code from sendfile */
  
    open_file = open(file_name, O_RDONLY);/* check that source file exists and can be opened */ 
    fstat(open_file, &stat_buf);         /* get size and permissions of the source file */
   
  
	set_header(header,status_code,file_name,(int)stat_buf.st_size);
	sent_size=send(socket, header, strlen(header), 0);
	
	
    /* copy file using sendfile ####################################### */
    // sendfile(destination, source, offset,size);
    return_code = sendfile (socket, open_file, &offset, stat_buf.st_size);
    printf("file size %d Bytes \n\n",return_code);
    
    if (return_code == -1) {
        fprintf(stderr, "error from sendfile: %s\n", strerror(errno));
 	}
 	else if (return_code != stat_buf.st_size) {
        fprintf(stderr, "incomplete transfer from sendfile: %d of %d bytes\n", return_code, (int)stat_buf.st_size); 
    }
    /* clean up and exit */
    close(socket);
    close(open_file);
    return 0;

}

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

        if (ini_parse(CONFIGURATION_FILE , handler, &config) < 0) {
                printf("Can't load 'ask.ini'\n");
                return 1;
        }
         printf("Config loaded from 'ask.ini':\nversion=%d\nbacklog=%d\nmax_header_size=%d \nhttp_version=%s\n",
        config.version, config.backlog, config.max_header_size, config.http_version);
        
	int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
	struct addrinfo hints, *servinfo, *p;
	struct sockaddr_storage their_addr; // connector's address information
	socklen_t sin_size;
	struct sigaction sa;
	int yes=1;
	char s[INET6_ADDRSTRLEN];
	int rv;

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE; // use my IP

	if ((rv = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}

	// loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("server: socket");
			continue;
		}

		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
				sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("server: bind");
			continue;
		}

		break;
	}

	if (p == NULL)  {
		fprintf(stderr, "server: failed to bind\n");
		return 2;
	}

	freeaddrinfo(servinfo); // all done with this structure

	if (listen(sockfd, config.backlog) == -1) {
		perror("listen");
		exit(1);
	}

	sa.sa_handler = sigchld_handler; // reap all dead processes
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	if (sigaction(SIGCHLD, &sa, NULL) == -1) {
		perror("sigaction");
		exit(1);
	}

	printf("ASK_SERVER: waiting for connections...\n");

	while(1) {  // main accept() loop
		sin_size = sizeof their_addr;
		new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
		if (new_fd == -1) {
			perror("accept");
			continue;
		}

		inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s);
		printf("ASK_SERVER: got connection from %s\n", s);

		if (!fork()) { // this is the child process
			close(sockfd); // child doesn't need the listener
			int buffer_size =1024;
			char* char_buffer = malloc(buffer_size);
			//get the client request
			read(new_fd,char_buffer,buffer_size);
			char *path;
  		    //printf("REQUEST ------ %s \n",char_buffer);
			//printf("CHECK_REQUEST %s \n",check_request(char_buffer));
			char* request_type = check_request(char_buffer);
			printf("REQUEST TYPE ::::::: %s\n",request_type);
			char* header=malloc(200);
  		    memset(header,0,200);
            
            if(request_type==NULL){	  	
  			    set_header(header,400,NULL,0);
  			    send(new_fd, header, strlen(header), 0);
  			    return 0;
  			}
  		    else if(strcmp(request_type,"POST")==0){
  			    set_header(header,501,NULL,0);
  			    send(new_fd, header, strlen(header), 0);
  			    return 0;
  		    }   
  		    
  		    path = get_path(char_buffer);
  		    if(strcmp("/",path)==0){
  		        path = (char*)config.default_page;
  		        // path = config.default_page;
  		    }
  		    char *root_dir=malloc(100);
			memset(root_dir,0,sizeof root_dir);
			strcpy(root_dir,config.root_dir);			
			path=strcat(root_dir,path);
			//printf("11111111111 real %s \n", path);
			
			/* ******* REQUEST FILE FOUND ********** */
  		    if(access(path, F_OK ) != -1){
				 send_content(path,new_fd,200);
				 //printf("OKKKKKKKKK %s \n", path);
			}
  		    else{					
				memset(root_dir,0,100);
				strcpy(root_dir,config.root_dir);
				path=strcat(root_dir,"/");
				path=strcat(root_dir,config.error_page);
				//printf("ERRRRRRRRRRORRR %s \n",path);
				send_content(path,new_fd,404);	
			}
  		    
			
		//	if (send(new_fd, "Hello, world!", 13, 0) == -1)
		//		perror("send");
		    free(char_buffer);
			close(new_fd);
			exit(0);
		}
		close(new_fd);  // parent doesn't need this
	}	
	
        printf("Config loaded from 'ask.ini': version=%d, backlog=%d,max_header_size=%d ,  http_version=%s\n",
        config.version, config.backlog, config.max_header_size, config.http_version);
        return 0;
		
}

I have included a sample www folder in the same directory to simulate the web server.

Download the full project from here.... DOWNLOAD

How to Test the Sample ASK Server.

Open a Terminal and Type the Following Commands.

[aruna@ubuntu]~$ makefile

[aruna@ubuntu]~$ ./askserver 7788


The argument 7788 is the port that we bind the webserver. Now open a web browser and type the following address localhost:7788

You'll see the web server is up and running. :)