Graphics Programs Reference
In-Depth Information
write(logfd, "Starting up.\n", 15);
host_addr.sin_family = AF_INET; // Host byte order
host_addr.sin_port = htons(PORT); // Short, network byte order
host_addr.sin_addr.s_addr = INADDR_ANY; // Automatically fill with my IP.
memset(&(host_addr.sin_zero), '\0', 8); // Zero the rest of the struct.
if (bind(sockfd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1)
fatal("binding to socket");
if (listen(sockfd, 20) == -1)
fatal("listening on socket");
while(1) { // Accept loop.
sin_size = sizeof(struct sockaddr_in);
new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
if(new_sockfd == -1)
fatal("accepting connection");
handle_connection(new_sockfd, &client_addr, logfd);
}
return 0;
}
/* This function handles the connection on the passed socket from the
* passed client address and logs to the passed FD. The connection is
* processed as a web request and this function replies over the connected
* socket. Finally, the passed socket is closed at the end of the function.
*/
void handle_connection(int sockfd, struct sockaddr_in *client_addr_ptr, int logfd) {
unsigned char *ptr, request[500], resource[500] , log_buffer[500] ;
int fd, length;
length = recv_line(sockfd, request);
sprintf(log_buffer, "From %s:%d \"%s\"\t", inet_ntoa(client_addr_ptr->sin_addr),
ntohs(client_addr_ptr->sin_port), request);
ptr = strstr(request, " HTTP/"); // Search for valid-looking request.
if(ptr == NULL) { // Then this isn't valid HTTP
strcat(log_buffer, " NOT HTTP!\n");
} else {
*ptr = 0; // Terminate the buffer at the end of the URL.
ptr = NULL; // Set ptr to NULL (used to flag for an invalid request).
if(strncmp(request, "GET ", 4) == 0) // Get request
ptr = request+4; // ptr is the URL.
if(strncmp(request, "HEAD ", 5) == 0) // Head request
ptr = request+5; // ptr is the URL.
if(ptr == NULL) { // Then this is not a recognized request
strcat(log_buffer, " UNKNOWN REQUEST!\n");
} else { // Valid request, with ptr pointing to the resource name
if (ptr[strlen(ptr) - 1] == '/') // For resources ending with '/',
strcat(ptr, "index.html"); // add 'index.html' to the end.
strcpy(resource, WEBROOT); // Begin resource with web root path
strcat(resource, ptr); // and join it with resource path.
fd = open(resource, O_RDONLY, 0); // Try to open the file.
Search WWH ::




Custom Search