Code:
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
int main() {
int s,n;
unsigned fd;
struct sockaddr sin={AF_INET,{31,144,0,0,0,0,0,0,0,0,0,0,0,0}};
WSADATA wsaData;
char *header="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
char data[512];
char filename[256];
FILE *f;
WSAStartup(MAKEWORD(1, 1), &wsaData); // initialise windows sockets
s=socket(PF_INET,SOCK_STREAM, 0); // create a socket
bind(s,&sin, sizeof(sin)); // bind it to port 80
listen(s,10); // allow up to 10 incoming connections
while(1) {
fd=accept(s,NULL,NULL); // wait for a request
n=recv(fd,data,512,0); // recieve the request using fd
data[n]=0; // NUL terminate it
sscanf(data,"GET /%s ",filename); // get the name of the file
f=fopen(filename,"rb"); // open the file (might be binary)
send(fd,header,strlen(header),0); // send the header
//
//file size
long lSize;
fseek (f,0,SEEK_END);
lSize = ftell(f);
rewind(f);
// allocate memory
char *buffer;
buffer = (char*)malloc(sizeof(char)*lSize);
if (buffer == NULL){
fputs ("Read error",stderr);
exit(1);
}
//copy file to buffer
size_t result;
result = fread(buffer,1,lSize,f);
if (result != lSize){
fputs("Read error",stderr);
exit(2);
}
//send buffer content to browser
send(fd,buffer,strlen(buffer),0);
//
closesocket(fd); // close the socket
fclose(f); //close file
free (buffer); //empty buffer
return 0; // send the file
//
//closesocket(fd); // close the socket
}
}