Hiya, i'm new to c++ and am struggling.
Atm i am doing some tasks to help me learn, up untill now i have been fine but for this one i am completely stuck with no clue where to go. (other than here of course)
i've been given a really cut down snippet of code and the tasks are to make it:
return pages to a real WWW client(only needs to do get requests)
must use its own port
return content type
server should always send a "Connection : close"
return content length and when it was last modified
correct error message where appropriate
If you could point me in the right direction as to how do these requirements that would be great.
Also if you could explain how this code is actually working that would be a great help too.
CODE
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
using namespace std;
extern void *serve(void *);
int main(int argc, char *argv[]){
int port = htons(atoi(argv[1]));
char buffer[4096];
int ssock, connsock, stat, r;
struct sockaddr_in myaddr;
ssock = socket(AF_INET, SOCK_STREAM, 0);
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = port;
stat=bind(ssock,(struct sockaddr *)&myaddr,sizeof(myaddr));
if(stat < 0) { cerr << "cant bind\n"; exit(1);}
listen(ssock,5);
pthread_t th;
while(true) {
connsock=accept(ssock,0,0);
r=pthread_create(&th,0,serve,(void *)connsock);
}
}
void *serve(void *s) {
int sock = (int)s, rc;
char buffer[2048];
const char *reply="HTTP/1.0 501 Method Not Implemented\r\n\r\n<h1>sorry</h1>\r\n";
pthread_detach(pthread_self());
rc = read(sock,buffer,2048);
write(1,buffer,rc);
write(sock,reply,strlen(reply));
close(sock); pthread_exit(0);
}