Code:
#include <stdio.h>
#include <winsock.h>
#include <windows.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 *sbuffer;
char filename[256];
long filesize;
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
//
// send the file
if (f==NULL) {
printf("File not exit.\r\n");
}
else
{
// obtain file size.
fseek (f,0,SEEK_END);
filesize = ftell (f);
rewind (f);
// allocate memory to contain the whole file.
sbuffer = (char*) malloc (filesize);
if (sbuffer == NULL) {
printf("memory error.\r\n");
}
else{
printf("Sending %s, size: %ld.\r\n",filename,filesize);
while (!feof(f)){
fread (sbuffer,1,filesize,f);
send(fd,sbuffer,strlen(sbuffer),0);
}//end of while
printf("Completed.\r\n");
}//end of else
} //end of else
closesocket(fd); // close the socket
}//end of while
//fclose(f);
}