Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
remzi-arpacidusseau
GitHub Repository: remzi-arpacidusseau/ostep-projects
Path: blob/master/concurrency-webserver/src/wclient.c
909 views
1
//
2
// client.c: A very, very primitive HTTP client.
3
//
4
// To run, try:
5
// client hostname portnumber filename
6
//
7
// Sends one HTTP request to the specified HTTP server.
8
// Prints out the HTTP response.
9
//
10
// For testing your server, you will want to modify this client.
11
// For example:
12
// You may want to make this multi-threaded so that you can
13
// send many requests simultaneously to the server.
14
//
15
// You may also want to be able to request different URIs;
16
// you may want to get more URIs from the command line
17
// or read the list from a file.
18
//
19
// When we test your server, we will be using modifications to this client.
20
//
21
22
#include "io_helper.h"
23
24
#define MAXBUF (8192)
25
26
//
27
// Send an HTTP request for the specified file
28
//
29
void client_send(int fd, char *filename) {
30
char buf[MAXBUF];
31
char hostname[MAXBUF];
32
33
gethostname_or_die(hostname, MAXBUF);
34
35
/* Form and send the HTTP request */
36
sprintf(buf, "GET %s HTTP/1.1\n", filename);
37
sprintf(buf, "%shost: %s\n\r\n", buf, hostname);
38
write_or_die(fd, buf, strlen(buf));
39
}
40
41
//
42
// Read the HTTP response and print it out
43
//
44
void client_print(int fd) {
45
char buf[MAXBUF];
46
int n;
47
48
// Read and display the HTTP Header
49
n = readline_or_die(fd, buf, MAXBUF);
50
while (strcmp(buf, "\r\n") && (n > 0)) {
51
printf("Header: %s", buf);
52
n = readline_or_die(fd, buf, MAXBUF);
53
54
// If you want to look for certain HTTP tags...
55
// int length = 0;
56
//if (sscanf(buf, "Content-Length: %d ", &length) == 1) {
57
// printf("Length = %d\n", length);
58
//}
59
}
60
61
// Read and display the HTTP Body
62
n = readline_or_die(fd, buf, MAXBUF);
63
while (n > 0) {
64
printf("%s", buf);
65
n = readline_or_die(fd, buf, MAXBUF);
66
}
67
}
68
69
int main(int argc, char *argv[]) {
70
char *host, *filename;
71
int port;
72
int clientfd;
73
74
if (argc != 4) {
75
fprintf(stderr, "Usage: %s <host> <port> <filename>\n", argv[0]);
76
exit(1);
77
}
78
79
host = argv[1];
80
port = atoi(argv[2]);
81
filename = argv[3];
82
83
/* Open a single connection to the specified host and port */
84
clientfd = open_client_fd_or_die(host, port);
85
86
client_send(clientfd, filename);
87
client_print(clientfd);
88
89
close_or_die(clientfd);
90
91
exit(0);
92
}
93
94