read requests
This commit is contained in:
parent
068a6e2e70
commit
ce055c56f6
20
webserver.c
20
webserver.c
|
@ -10,7 +10,7 @@
|
|||
|
||||
int main() {
|
||||
char buffer[BUFFER_SIZE];
|
||||
char resp[] = "HTTP/1.0 200\r\n"
|
||||
char resp[] = "HTTP/1.0 200 OK\r\n"
|
||||
"Server: webserver-c\r\n"
|
||||
"Content-type: text/html\r\n\r\n"
|
||||
"<html>hello, world</html>\r\n";
|
||||
|
@ -18,7 +18,7 @@ int main() {
|
|||
// create a socket
|
||||
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd == -1) {
|
||||
perror("webserve (socket)");
|
||||
perror("webserver (socket)");
|
||||
return 1;
|
||||
}
|
||||
printf("socket created successfully\n");
|
||||
|
@ -31,6 +31,10 @@ int main() {
|
|||
host_addr.sin_port = htons(PORT);
|
||||
host_addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
|
||||
// create client address
|
||||
struct sockaddr_in client_addr;
|
||||
int client_addrlen = sizeof(client_addr);
|
||||
|
||||
// Bind the socket to the address
|
||||
if (bind(sockfd, (struct sockaddr *) &host_addr, host_addrlen) != 0) {
|
||||
perror("webserver (bind)");
|
||||
|
@ -54,6 +58,13 @@ int main() {
|
|||
}
|
||||
printf("connection accepted\n");
|
||||
|
||||
// get client address
|
||||
int sockn = getsockname(newsockfd, (struct sockaddr *) &client_addr, (socklen_t *) &client_addrlen);
|
||||
if(sockn < 0) {
|
||||
perror("webserver (getsockname)");
|
||||
continue;
|
||||
}
|
||||
|
||||
// read from the socket
|
||||
int valread = read(newsockfd, buffer, BUFFER_SIZE);
|
||||
if (valread < 0) {
|
||||
|
@ -61,6 +72,11 @@ int main() {
|
|||
continue;
|
||||
}
|
||||
|
||||
// read the request
|
||||
char method[BUFFER_SIZE], uri[BUFFER_SIZE], version[BUFFER_SIZE];
|
||||
sscanf(buffer, "%s %s %s", method, uri, version);
|
||||
printf("[%s:%u] %s %s %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), method, version, uri);
|
||||
|
||||
// write to the socket
|
||||
int valwrite = write(newsockfd, resp, strlen(resp));
|
||||
if (valwrite < 0) {
|
||||
|
|
Loading…
Reference in New Issue